Skip to content
Latchkey

Bash Scripting Cheat Sheet: Variables, Tests & Loops

Bash syntax for variables, conditionals, loops, and safe scripting in one place.

The bash constructs you reach for when writing CI and automation scripts.

Strict mode & variables

script.sh
#!/usr/bin/env bash
set -euo pipefail

name="${1:-default}"        # default if unset
count=${#array[@]}          # array length
echo "${PATH%%:*}"          # first path entry

Parameter expansion

FormResult
${var:-x}x if var unset/empty
${var:=x}Assign x if unset
${var:?msg}Error msg if unset
${var#pat}Strip shortest prefix
${var%pat}Strip shortest suffix
${var/old/new}Replace first match
${#var}String length

Test conditions

TestTrue when
[[ -f f ]]File exists
[[ -d d ]]Directory exists
[[ -z s ]]String empty
[[ -n s ]]String non-empty
[[ a == b ]]String equal
(( a > b ))Arithmetic compare

Loops

loops
for f in *.txt; do echo "$f"; done
while read -r line; do echo "$line"; done < file
case "$x" in
  start) run ;;
  *) echo "unknown" ;;
esac

Key takeaways

  • set -euo pipefail catches errors, unset vars, and broken pipes.
  • Always quote "${var}" to survive spaces and globbing.
  • [[ ]] is the safer modern test; (( )) for arithmetic.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →