Bash Scripting File Manipulation Examples and Reference

Last updated:
Table of Contents

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

check 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

check 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

iterate through files in 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

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

DIR=$(pwd)

references

Dialogue & Discussion