Saturday, July 24, 2010

Listing Hidden Files in Bash

I decided it would be useful to have an alias to display all the hidden files in a directory, but wanted a bit more than just a simple alias to 'ls -Ad .**' as this only allows you to list the current directory. Aliasing 'ls -Ad $*.**' worked, but didn't provide any room for error checking regarding trailing directory slashes. There was also the grep option, but that messes with the nice column formatting ls provides so I scrapped that idea.

In short, I decided to write up a function with a short name that I could use as an alias:

# list only hidden files in the given directory(s)
function lh() {

# if directories were given
if [ $# -gt 0 ]; then

# store current dir so we can come back
startingPath=`pwd`

# loop through input dirs
for i in $*; do

# only list contents for directories
if [ -d $i ]; then
cd $i # cd to the directory
echo $i: # print a header
ls -Ad .** # list hidden files
else
echo Ignoring directory: $i
fi

echo # blank line for readability

done

# cd back to your original directory
cd $startingPath

else

# just list hidden files for current directory
ls -Ad .**

fi
}

No comments:

Post a Comment