Bash

Bash scripting essentials - variables, conditionals, loops, functions and safe defaults.

Shell #bash#scripting#shell Last updated
Library

Safe script header#

#!/usr/bin/env bash
set -euo pipefail          # exit on error, unset vars, failed pipes
IFS=$'\n\t'

Variables and strings#

name="world"
echo "Hello, ${name}!"
echo "${name^^}"           # uppercase
echo "${#name}"            # length
file="report.tar.gz"
echo "${file%%.*}"         # report
echo "${file#*.}"          # tar.gz
echo "${missing:-default}" # default when unset or empty

Conditionals#

if [[ -f config.yml ]]; then
  echo "config exists"
elif [[ -d config ]]; then
  echo "config is a directory"
else
  echo "no config"
fi
Test True when
-f path Regular file exists
-d path Directory exists
-z "$s" String is empty
-n "$s" String is not empty
"$a" == "$b" Strings are equal
$a -lt $b Integer less than

Loops#

for f in *.log; do
  gzip "$f"
done

while read -r line; do
  echo "line: $line"
done < input.txt

for i in {1..5}; do echo "$i"; done

Functions#

greet() {
  local who="${1:?usage: greet NAME}"
  printf 'Hello, %s\n' "$who"
}
greet "Ada"

Arrays#

items=(alpha beta gamma)
echo "${items[0]}"
echo "${#items[@]}"
for item in "${items[@]}"; do echo "$item"; done

Redirection#

cmd > out.txt 2>&1     # stdout and stderr to a file
cmd 2>/dev/null        # discard errors
cmd | tee log.txt      # show and save output

Back to library

Keyboard shortcuts

/
Focus search
Esc
Close dialogs, menus and messages
?
Show this help
Ctrl S
Save in the admin editor