Bash Scripting File Manipulation Examples and Reference

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"

Loop over files in directory

Example: print the file name of each file under some/path/:

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

Loop over files in directory, one liner

Example: print the file name of each file under some/path/:

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

Loop over 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 file directory

Get the path to the directory where this 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)

Dialogue & Discussion