Go read this cheat-sheet (archive) instead of this file.
A more thorough guide (as opposed to a cheat-sheet) is the BashGuide (archive).
The Bash man page (archive) is also great.
#!/bin/bash
set -euo pipefailFrom: Bash Strict Mode
The argument to if or elif is a statement, and every statement in sh/bash has a return-value. For the purposes of if, a return value of 0 is true/succes, non-zero is false/failure.
if <condition>; then
# more statements
fiOr:
if <condition>; then
# if-body
elif <condition>; then
# else-if
else
# else
fiCommon statements used as if bodies:
if git diff --quiet; then
# repo has changes
fiif test -f "$file"; then
# file exists
fiif [ -f "$file" ]; then
# the "]" argument to "test" is ignored, but is mandatory
fiif [[ -f $file ]]; then
# '[[' is a Bash built-in with nicer behavior than '[' or 'test'
fiif [[ -a "$file" ]]; then
# do thing
fiif [[ -f "$file" ]]; then
# do thing
fiif [[ -d "$file" ]]; then
# do thing
fiif [[ -n "$var" ]]; then
# do thing
fiif [[ -z "$var" ]]; then
# do thing
fiif ! command -v fooBar; then
echo "fooBar not found!"
exit 1
fifunction fun_name() {
# create a function-scoped variable,
# reference the first and second parameters
local x="$1 + $2"
printf "%s" "$x"
}temp_file=$(mktemp)
if [[ ! -f "$temp_file" ]]; then
echo "Unable to allocate temp-file"
exit 1
fi
function cleanup() {
rm -f "$temp_file"
}
trap cleanup EXIT
# now do something with your temp-file# Allocate an entire folder, register to clean it up
temp_dir=$(mktemp -d)
if [[ ! -d "$temp_dir" ]]; then
echo "Unable to allocate temporary directory"
exit 1
fi
function cleanup() {
rm -rf "$temp_dir"
}
trap cleanup EXIT
# Allocate files within the folder
file1=$(mktemp -p "$temp_dir")
file2=$(mktemp -p "$temp_dir")
# Or used fixed file-names - the
# folder should have been created
# with permissions 700.
file3="$temp_dir/foo.txt"
# now do something with the filesThis isn’t exactly portable across the different implementations of mktemp - if you need portability the script should define the TMPDIR variable instead of relying on/using the -p argument (some OSes do not have -p, in others -p is ignored if TMPDIR is set). But for GNU this is fine.