if [[ -f /etc/hosts ]]; then echo yes; fi[[ ... ]] is generally safer and more expressive than [ ... ].
Bash if/elif/case logic, test expressions, loops, functions, return codes, and robust control-flow patterns.
Use test, [, [[, and arithmetic conditions.
if [[ -f /etc/hosts ]]; then echo yes; fi[[ ... ]] is generally safer and more expressive than [ ... ].
if [[ -d /var/log ]]; then echo yes; fiUseful before cd, mkdir, or file operations.
if [[ -z "$name" ]]; then echo empty; fiQuote variable expansions inside tests.
if [[ "$env" == 'prod' ]]; then echo deploy; fi[[ supports pattern matching with == as well.
if (( count > 10 )); then echo large; fiCleaner than -gt for many Bash scripts.
if grep -q needle file.txt; then echo found; fiShell conditions commonly use exit status rather than booleans.
case "$ext" in
jpg|png) echo image ;;
txt) echo text ;;
*) echo other ;;
esaccase is usually clearer than many if/elif checks.
for, while, until, and select loops.
for f in *.log; do echo "$f"; donePair with nullglob when patterns may not match.
for ((i=0; i<5; i++)); do echo "$i"; doneHelpful for counters and indexed arrays.
while IFS= read -r line; do printf '%s
' "$line"; done < file.txtCommon in parsing and scripting.
until curl -sf http://localhost:8080/health; do sleep 1; doneGood for readiness checks in scripts.
for n in {1..5}; do [[ $n -eq 3 ]] && continue; echo "$n"; doneFundamental control-flow building blocks.
select choice in start stop status quit; do echo "$choice"; break; doneUseful for interactive admin helpers.
Define reusable Bash functions and control return behavior.
greet() { echo "Hello, $1"; }Bash supports both name() { ... } and function name { ... } forms.
greet JonathanFunction arguments are available as positional parameters inside the function.
work() { local dir=${1:-/tmp}; cd "$dir" || return 1; pwd; }local is a Bash builtin, not POSIX sh.
validate() { [[ -n "$1" ]] || return 1; }return is for status codes, not arbitrary values.
slugify() { tr '[:upper:] ' '[:lower:]-' <<< "$1"; }
slug=$(slugify 'Hello World')This is the most common shell pattern for function 'return values'.
set -x
my_func() { echo ok; }
my_func
set +xUseful when debugging control flow and variable expansion.
Safer Bash defaults for production scripts.
set -euo pipefailPopular baseline for defensive scripting, though you should still understand edge cases.
IFS=$'
\t'Sometimes used with strict scripts to reduce splitting surprises.
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXITVery common when using temp files or temp dirs.
trap 'echo "error on line $LINENO"' ERRHelpful when paired with set -e.
# shellcheck disable=SC2086
echo $unquotedUseful when you use ShellCheck in CI.