Bash Scripting File Manipulation Examples and Reference

Last updated:
Table of Contents

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

check whether a directory exists

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

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"

get current directory

Get the path to the directory where the current file is located

HEADS-UP This is not the current working directory!

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

get current working directory

Get the directory the script's caller is located when he executed this script



Dialogue & Discussion