Bash Scripting File Manipulation Examples and Reference

Last updated:

check whether a file exists

apparently, -a should work too but I've had some issues with it and -e seems to work better.

if [ -e "/path/to/file" ]; then
    #file exists
elif [ ! -e "/path/to/file"]; then
    # file doesn't exist
fi

check whether a directory exists

if [ -d "/path/to/directory" ]; then
    # directory exists
elif [ ! -d "/path/to/directory" ]; then
    # directory doesn't exist
fi

iterate through files in a directory

HEADS-UP If you want to include hidden files (begin with .), you need to enable dotglob via shopt -s dotglob before the for-loop.

for f in some/path/*; do
  echo "$f"
done

references

Dialogue & Discussion