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
set -euo pipefail
-e
: exit when a command exits with non-zero status-u
: exit on undefined variable-o pipefail
: set return value ofcmd1 | cmd2 | cmd3
to last command to exit with non-zero status (instead of exit status ofcmd3
by default)
set -x
to print each command as it is run- Wrap the script in
main() { ... }
and putmain "$@"
at the bottom.- Forces Bash to load and parse entire file before beginning execution.
Be careful
- If you press Ctrl+Z in a compound command (
cmd1 && cmd2
, afor
loop, etc.), then when you runfg
only the command that was interrupted will be resumed, not the whole compound command. Try it yourself:sleep 5 && echo done
ln -sf target name
is supposed to replace the symlink atname
with one pointing totarget
, but ifname
is a directory, it instead creates a symlinkname/target
that points attarget
.