Bash Scripting File Manipulation Examples and Reference

Last updated:
Table of Contents

In Bash, whitespace within [[ and ]] is not optional!!

If file exists

Returns true if the file exists (must be a file, not a directory), even if you don't have read access to it

if [[ -f "/path/to/file" ]]; then
    # file exists
elif [[ ! -f "/path/to/file" ]]; then
    # file doesn't exist or it's not a regular file
fi

File exists, one-liner

[[ -f "/path/to/file" ]] && echo "file exists"

If directory exists

if [[ -d "/path/to/directory" ]]; then
    # file exists and it's a directory
elif [[ ! -d "/path/to/directory" ]]; then
    # file doesn't exist or it's not a directory
fi

Directory exists, one-liner

[[ -d "/path/to/directory" ]] && echo "directory exists"

Iterate through files in directory

# loop through files, does not include hidden files
for f in some/path/*; do
  echo "$f"
done

Iterate through files in directory, include hidden

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

shopt -d dotglob

# loop through files, including hidden files
for f in some/path/*; do
  echo "$f"
done

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 )"

Current working directory

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

DIR=$(pwd)

Directory of current file

See above: current directory

Dialogue & Discussion