Your DevOps study space

Real explanations. Videos with tests. Fresh exams every time. Keep the streak alive and watch the XP stack up.

Shell scripting · Linux Docs · StackwisePlanDevOps Shell scripting · Linux Docs · StackwiseCodePython Shell scripting · Linux Docs · StackwiseBuildDocker Shell scripting · Linux Docs · StackwiseTestDevOps Shell scripting · Linux Docs · StackwiseReleaseGit Shell scripting · Linux Docs · StackwiseDeployKubernetes Shell scripting · Linux Docs · StackwiseOperateLinux Shell scripting · Linux Docs · StackwiseMonitorDevOps

Pick a topic

Eight tracks, each with docs, a cheat sheet, videos and tests.

How it works

One loop, repeated until it sticks.

Jump back in

Picked up from where you left off.

Free forever

Your DevOps journey starts with one click.

Sign in with Google or GitHub to open every chapter, video, test and challenge. Your progress is saved wherever you learn.

Shell scripting

The debugging chapter showed a tiny backup script. This chapter goes properly into bash scripting: how variables and quoting really work, how scripts make decisions and loop, and how to write scripts that stop loudly when something breaks instead of carrying on and doing damage.

Running a script

The first line, the shebang, tells Linux which program should run the file. #!/bin/bash points straight at bash; #!/usr/bin/env bash asks env to find bash in your PATH, which also works on systems where bash lives somewhere else (macOS with a newer bash, for example).

$ ./backup.sh              # needs the execute bit and uses the shebang
bash: ./backup.sh: Permission denied
$ chmod +x backup.sh       # fix: make it executable
$ ./backup.sh              # runs in a new bash process
$ bash backup.sh           # also works without +x (bash is the program, the file is its input)
$ source backup.sh         # runs inside YOUR current shell (used for config files, not scripts)

The ./ is needed because the current folder is not in PATH. Avoid sh backup.sh on Ubuntu: sh is dash, a smaller shell that ignores the shebang and doesn't understand bash features like [[ ]], so you get errors such as [[: not found.

Variables and quoting

name="web-01"                 # no spaces around = (name = x runs a command called "name")
today=$(date +%F)             # command substitution: 2026-09-27
count=$((3 + 4))              # arithmetic: 7
echo "Server $name on $today" # double quotes: variables ARE expanded
echo 'Server $name'           # single quotes: printed literally -> Server $name
echo "${name}-backup.tar.gz"  # braces mark where the name ends
echo "${ENVIRONMENT:-dev}"    # use "dev" if ENVIRONMENT is unset or empty
: "${API_KEY:?API_KEY must be set}"   # stop the script with this message if it's missing

Always put variables in double quotes. Unquoted, bash splits the value on spaces and expands wildcards, so a file called my notes.txt becomes two arguments:

file="my notes.txt"
rm $file      # tries to delete "my" and "notes.txt"
rm "$file"    # deletes the one file you meant

Arguments

VariableMeaning
$0the script's own name, as it was called
$1, $2…the first, second… argument (${10} from ten on)
$#how many arguments were given
"$@"all arguments, each kept as a separate word. Use this form to pass them on or loop over them
$?exit code of the last command

Exit codes, && and ||

Every command ends with an exit code: 0 means success, 1–255 mean some kind of failure, and each program documents its own codes. grep, for example, returns 0 if it found a match, 1 if it didn't and 2 on an error.

$ ls /nope
ls: cannot access '/nope': No such file or directory
$ echo $?
2
$ mkdir -p /tmp/build && cd /tmp/build     # && runs the second only if the first succeeded
$ ping -c1 db-01 || echo "db-01 is down"     # || runs the second only if the first failed

Your own script sets its exit code with exit 0 or exit 1. Cron, CI pipelines and monitoring tools look only at this number to decide whether your script worked.

ping -c1 db-01sets $?exit code 0success: && runs the nextexit code 1-255failure: || runs the nextworkedfailed
&& and || only look at that one number. So do cron, CI pipelines and monitoring tools.

Conditions: if, [ ] and [[ ]]

if runs a command and checks its exit code. [ ... ] (also called test) and bash's improved [[ ... ]] are just commands that succeed or fail. The spaces inside the brackets are required: [$x -gt 3] fails with [5: command not found.

if [[ -f /etc/nginx/nginx.conf ]]; then
  echo "nginx config found"
elif [[ -d /etc/apache2 ]]; then
  echo "looks like apache"
else
  echo "no web server config" >&2
fi

if grep -q "ERROR" app.log; then     # any command works as a condition
  echo "errors in the log"
fi

if (( disk_used >= 90 )); then echo "disk almost full"; fi   # (( )) for numbers
TestTrue when
-f path / -d path / -e pathis a file / is a directory / exists at all
-z "$s" / -n "$s"string is empty / not empty
"$a" == "$b", !=strings equal / different
-eq -ne -lt -le -gt -genumber comparisons (< inside [[ ]] compares text, not numbers)
[[ $f == *.log ]]pattern match (only in [[ ]])
! test, &&, ||not, and, or

Loops

for host in web-01 web-02 db-01; do        # over a list of words
  ssh "$host" uptime
done

for f in /var/log/myapp/*.log; do          # over files (quote "$f"!)
  gzip "$f"
done

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

while IFS= read -r line; do                # a file line by line
  echo "host: $line"
done < hosts.txt

until curl -fs http://localhost:8080/health > /dev/null; do   # retry until it works
  sleep 2
done

IFS= read -r is the safe way to read lines: it keeps leading spaces and backslashes exactly as they are in the file.

Functions and reading input

greet() {
  local who="$1"            # local: the variable disappears when the function ends
  echo "hello $who"
}
greet "Demee"

read -rp "Deploy to production? [y/N] " answer
if [[ "$answer" == "y" ]]; then echo "deploying..."; fi
read -rsp "Password: " pw; echo   # -s hides what you type

Arguments inside a function are $1, $2… of that call, not of the script. A function's return sets its exit code (0–255); to hand back text, echo it and capture it with result=$(myfunc).

Strict mode: set -euo pipefail

By default bash ignores failures and keeps going. Put this line under the shebang of every serious script:

  • -e: exit as soon as a command fails (except inside if conditions and &&/|| chains, where failure is expected).
  • -u: using a variable that was never set is an error (unbound variable) instead of silently being empty. That stops rm -rf "$DIR/" turning into rm -rf / because of a typo in the name.
  • -o pipefail: a pipeline fails if any part fails, not just the last. Without it, false | true counts as success.

trap cleanup EXIT runs a function called cleanup whenever the script ends, even after an error, which is the place to delete temp files.

A complete example: health check

#!/usr/bin/env bash
# healthcheck.sh - check free disk space and that some URLs answer
set -euo pipefail

THRESHOLD="${THRESHOLD:-90}"        # override: THRESHOLD=80 ./healthcheck.sh ...
LOG_FILE="${LOG_FILE:-/tmp/healthcheck.log}"
failures=0

log() {
  echo "$(date '+%F %T') $*" | tee -a "$LOG_FILE"
}

check_disk() {
  local mount="$1" used
  used=$(df --output=pcent "$mount" | tail -n 1 | tr -dc '0-9')
  if (( used >= THRESHOLD )); then
    log "FAIL disk $mount is ${used}% full"
    return 1
  fi
  log "ok   disk $mount is ${used}% full"
}

check_url() {
  local url="$1" code=0
  curl -fs -o /dev/null --max-time 5 "$url" || code=$?
  if (( code != 0 )); then
    log "FAIL $url (curl exit code $code)"
    return 1
  fi
  log "ok   $url"
}

if [[ $# -eq 0 ]]; then
  echo "usage: $0 URL [URL...]" >&2
  exit 2
fi

check_disk / || failures=$((failures + 1))
for url in "$@"; do
  check_url "$url" || failures=$((failures + 1))
done

if (( failures > 0 )); then
  log "$failures check(s) failed"
  exit 1
fi
log "all checks passed"
$ chmod +x healthcheck.sh
$ ./healthcheck.sh http://localhost:8080/ http://localhost:9000/health
2026-09-27 10:15:02 ok   disk / is 29% full
2026-09-27 10:15:02 ok   http://localhost:8080/
2026-09-27 10:15:02 FAIL http://localhost:9000/health (curl exit code 7)
2026-09-27 10:15:02 1 check(s) failed
$ echo $?
1

curl -f makes HTTP errors (4xx/5xx) count as failures. Its exit code tells you why: 6 = couldn't resolve the host name, 7 = couldn't connect, 22 = the server answered with an HTTP error, 28 = timed out. The next chapter shows how to run this every few minutes with cron.

Common mistakes

  • name = value gives name: command not found. Remove the spaces around =.
  • ((count++)) under set -e kills the script when count is 0, because (( )) returns failure when the result is 0. Use count=$((count + 1)).
  • A script written on Windows has CRLF line endings; bash then reports cannot execute: required file not found (older versions: /bin/bash^M: bad interpreter). Fix with sed -i 's/\r$//' script.sh or dos2unix.
  • Unquoted $var or $@ break on spaces. Quote them.
  • Install shellcheck (sudo apt install shellcheck) and run shellcheck script.sh: it catches most of these before you run anything.

Questions

Pick an answer. Get it wrong and you can try again right away, no waiting. 10 questions per topic - pick a filter below, then use Recreate questions for a fresh set on that topic.

Fresh questions every time

Exam

A mixed test across the whole site, shuffled so you never know which topic comes next. When you submit, every mistake comes with the reason and a jump to the exact moment in the video that explains it.

30 questions 6 topics 20 minute limit Up to 70 XP
1–4 answer · ←→ move
History

Essay

0 / 200-250 words
Sample answer
History
0:00 / 0:00
Not started

on YouTube
Subscribe

Topic progress

Activity

Achievements

Settings

Your profile and your account.

Profile details

* Required. Saved in this browser until you sign in.

Letters, numbers, dots, dashes and underscores.
0 / 160

Account

Checking…

App

Install Stackwise on your phone or computer. It opens in its own window from your home screen, and the Docs and cheat sheets you've opened keep working without internet.

Only admins can see this

Dashboard

Sign-ups, activity, messages and reviews in one place.

Prove it

Certificates

Pass a topic's test and get a certificate with its own public page you can share or add to LinkedIn. Each test is 10 questions drawn at random and graded on the server; you need 8 right, you have 15 minutes, and you get one try per topic a day.

From first command to production

Linux for DevOps

A path through Linux the way DevOps engineers use it: ten stages, every command explained with its flags, examples, real output and mistakes, the combinations engineers chain together, and incidents worked through step by step. Practise everything in a safe lab folder.

Before the interview

Interview prep

Questions that come up in real DevOps interviews, with the kind of answer that lands. Say yours out loud first, then compare. Each one links to the chapter that goes deeper.

    Private to you

    My notes

    Everything you wrote down while watching and reading, in one place. Saved to your account, never shown to anyone.