DevOps Tutorial · Linux and the Shell · Lesson 7 of 25

Shell Scripting Basics

Variables, conditions, loops, functions and exit codes: the bash you need for automation and CI steps.

Create a free account to save this page, take notes and track your progress. Sign in

Variables and quoting

name="web-api"            # no spaces around =
echo "deploying $name"     # double quotes expand variables
echo 'deploying $name'     # single quotes don't

Always quote variables ("$file"), or values with spaces break into several words.

Conditions, loops and functions

Loops, functions and return codes
services=("api" "worker" "web")

check() {
  local svc="$1"
  if [[ "$svc" == "worker" ]]; then
    echo "$svc: degraded"
    return 1
  fi
  echo "$svc: healthy"
}

failed=0
for svc in "${services[@]}"; do
  check "$svc" || failed=$((failed + 1))
done
echo "$failed service(s) need attention"

Output

api: healthy
worker: degraded
web: healthy
1 service(s) need attention

Run this on your computer — see “Get Started” for setup.

Exit codes

Every command returns an exit code: 0 means success, anything else is failure. $? holds the last one. CI systems fail a step when a command exits non-zero, and && / || chain commands on success or failure.

Exit codes with && and ||
grep -q "port" /etc/services && echo "found: exit code $?"
grep -q "no-such-thing" /etc/services || echo "not found: exit code $?"
mkdir build && cd build && echo "in $(basename "$PWD")"

Output

found: exit code 0
not found: exit code 1
in build

Run this on your computer — see “Get Started” for setup.

Command substitution and arithmetic

$(command) inserts a command's output; $(( )) does integer arithmetic.

Command substitution and arithmetic
version="1.4.2"
major="${version%%.*}"                 # strip everything after the first dot
files=$(printf 'a\nb\nc\n' | wc -l)
echo "major version: $major"
echo "next major:    $((major + 1)).0.0"
echo "line count:    $files"

Output

major version: 1
next major:    2.0.0
line count:    3

Run this on your computer — see “Get Started” for setup.

Test yourself

What does the exit code 0 mean?

  1. Success
  2. Failure
  3. Still running
  4. Killed by a signal
Show answer

Answer: Success

Zero is success; any non-zero value is a failure that CI steps and && chains react to.

Was this page helpful?