home blog portfolio Ian Fisher

Bash cheatsheet

See also: wiki/bash, ref/shell-commands

Strings

${s%suffix} # remove suffix
${s#prefix} # remove prefix
${s/from/to} # replace first occurrence
${s//from/to} # replace all occurrences

${x:-default} # variable or default value

Heredocs

cat << EOF
Line 1
Line 2
EOF

cat << "EOF"
No parameter expansion is done.
EOF

    cat <<- EOF
    The <<- operator lets you indent your code.
    EOF

s=$(cat << EOF
Line 1
Line 2
EOF
)

Control flow

for p in *.csv; do
  # ...
done

if [[ ... ]]; then
fi

case "$x" in
  pattern)
    ;;
  *)
    ;;
esac

Conditions

[[ "$s" == "prefix"* ]] # string has prefix
[[ -z "$s" ]] # string is empty
[[ -n "$s" ]] # string is not empty

[[ -e "$f" ]] # file exists
[[ -d "$f" ]] # file is directory
[[ -f "$f" ]] # file is regular file
[[ -h "$f" ]] # file is a symlink
[[ -x "$f" ]] # file is executable

(( x == 100 )) # no needs for '$'

Arrays

arr=()
arr+=("$x")
${#arr[@]} # array length
for x in "${arr[@]}"; do .. done

Temporary files and directories

tmp="$(mktemp)"
tmpdir="$(mktemp -d)"

# with specific extension
# https://stackoverflow.com/a/59638023/3934904
tmpdir="$(mktemp -d)"
tmp="$tmpdir/test.md"

Clean-up functions

cleanup() { ... }
trap cleanup EXIT

Get script path

SCRIPT_PATH="$(realpath "$0")"

Tips

Be careful