Skip to content

Instantly share code, notes, and snippets.

@awan1
Last active August 23, 2016 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awan1/ad35a801763af956f1e631187b58df92 to your computer and use it in GitHub Desktop.
Save awan1/ad35a801763af956f1e631187b58df92 to your computer and use it in GitHub Desktop.
An improved ls command that can exclude files matching given globs and shows how many of each file were excluded.
###########
## Notes ##
###########
## This shows you how to configure your ls command to not show certain files,
## and tell you how many of those files were omitted. This declutters your ls output.
## To use this, add it to whatever .{profile, alias, rc} file you put your aliases in.
## The ls and find functions here are the GNU variants: the flags needed are not in
## the BSD variant, which is the OSX default.
## So on OSX, you'll need to install GNU ls and GNU find (see http://goo.gl/bDO0ga),
## and if you don't use the ``default-names` option in brew either change `ls` and
## `find` to `gls` and `gfind` respectively, or do
## alias ls='gls'; alias find='gfind'
######################
## Begin definition ##
######################
## Globs here will be excluded from the output of ls
omit_globs=('*.pyc' 'xxx')
## Build the ignore args for the ls command
ignore_args=''
for omit_glob in ${omit_globs}; do
ignore_args="$ignore_args --ignore=\"${omit_glob}\""
done
## The main function
function lshide () {
## Set lsarg to the current directory if there were no arguments to ls;
## otherwise set it to the arguments.
## Allows ls with no arguments to work as expected.
lsarg=${@:-.}
## Build the ls command and run it, so that ignore_args gets properly
## parsed as the flags. This causes the ls output.
lscmd="ls $lsarg ${ignore_args}"
eval $lscmd
## Exit if ls failed
if [ $? -ne 0 ] ; then return; fi
## Count the number of files to omit
for omit_glob in ${omit_globs}; do
## Need to use the eval string again because lsarg could be a glob,
## and it's now a string because we used the noglob setting
find_cmd="find ${lsarg} -maxdepth 1 -iname \"${omit_glob}\""
## Counts the number of excluded files; the sed command formats the
## output of wc by stripping leading spaces and tabs
omit_count=$(eval $find_cmd | wc -l | sed -e 's/^[ \t]*//')
if [ $omit_count -gt 0 ] ; then
echo "Omitted ${omit_count} ${omit_glob} files"
fi
done
}
## Need noglob because we want to pass globs to the function without the shell
## expanding them first
alias ls="noglob lshide" ## Or whatever alias you want
####################
## Example output ##
####################
## $ ls
## < ls output >
## Omitted 9 .pyc files
## Omitted 1 xxx files
## The "omitted" line is not printed for any globs that weren't excluded
## (so if there were no .pyc files, that line wouldn't print)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment