How to learn the core shell scripting techniques

Learn in short repetitions with one technique per drill

Set aside 20–30 minutes a day and learn one technique at a time. Each drill should produce a 3–5 line script that does a single job: print a quoted variable, test whether a file exists, loop over three names, or capture a command’s output. Run the script, change one line, run it again, then break it deliberately and repair it.

Repeat the same drill 10 times over two days rather than copying ten different examples once. That repetition is what turns syntax into a working habit. Keep your experiments small enough to read in one screen; a 10-line script exposes misunderstandings faster than a 100-line one.

Master quoting and variables before anything else

Variables are assigned with no spaces around the equals sign: name="Ada Lovelace". Read the value back as "$name". Single quotes preserve literal text; double quotes allow expansion but also preserve spaces and prevent unwanted word splitting. Use braces when text follows the variable: "${name}_backup".

Your first 5 scripts should each contain at least one quoted variable. Test file="my report.txt" and print it with printf '%s\n' "$file". If the output shows two separate words, you have met the core quoting failure early. For lists, use an array and expand it as "${files[@]}"; for a possibly empty value, use "${name:-unknown}". Do not move on until quoted expansion feels automatic.

Use conditionals with real exit statuses

Every command returns an exit status: 0 means success, and 1–255 means some kind of failure. Check it immediately with $?, because the next command overwrites it. A basic test looks like if [[ -f "$file" ]]; then printf '%s\n' "found"; fi. Use [[ ]] for string and file tests, and (( )) for arithmetic.

Write 10 condition tests: file exists, file missing, string empty, string non-empty, two numbers equal, and so on. Then practise case for a small menu with 2–3 branches: case "$1" in start) ... ;; stop) ... ;; *) ... ;; esac. The point is not to memorise every operator but to learn the rhythm: test, branch, observe the exit status.

Write loops that survive spaces and blank lines

Use a glob loop for files: for file in *.txt; do printf '%s\n' "$file"; done. Use a read loop for line-by-line input: while IFS= read -r line; do printf '%s\n' "$line"; done < input.txt. Create 3 test files, including one named two words.txt, and include one blank line in the input. If your loop mishandles either case, the technique is not yet learned.

Avoid for x in $(ls) and other command-substitution loops that split names on spaces. For simple counting, for i in 1 2 3 4 5 is portable and clear. Always quote the loop variable when you use it: "$file", "$line".

Turn repeated blocks into functions with clear inputs

When the same 3 lines appear twice, make a function. A useful shape is make_backup() { local src="$1"; local dest="${2:-/tmp}"; cp -- "$src" "$dest" || return 1; }. Use local for variables inside the function, accept 2–4 arguments, and return 0 for success or 1 for failure. Call it with quoted arguments: make_backup "my report.txt" "/tmp".

While learning, write one function per script. Functions should send normal output to stdout and error messages to stderr. Avoid changing global variables from inside a function until you can explain why that is risky.

Pipe, redirect, and capture output deliberately

Learn the four common redirections: > truncates a file, >> appends, 2> captures errors, and 2>&1 merges errors into normal output. Test them with 3 small commands. A pipeline such as grep error app.log | wc -l counts matching lines; a capture such as count=$(grep -c error app.log) stores the result in a variable.

Send your own error messages to stderr with printf '%s\n' "missing file" >&2. Prefer grep pattern file over cat file | grep pattern; the shorter pipeline is easier to debug. After every pipe or redirect, inspect the output file or variable to confirm what actually happened.

Add error handling at the edges and debug with tracing

Start with set -u and set -o pipefail so unset variables and failing pipeline stages are visible. Add set -e only after you can explain which commands it will skip and why. For a critical step, write an explicit check: if ! cp -- "$src" "$dest"; then printf '%s\n' "copy failed" >&2; exit 1; fi. Use trap 'rm -f "$tmp"' EXIT when a temporary file must be cleaned up.

Debug with three tools: bash -n script.sh checks syntax, bash -x script.sh prints the commands as they run, and printf '<%s>\n' "$var" shows hidden spaces or empty values. Trace only 10 lines at a time; a long trace hides the first failure.

Diagnose the unquoted-variable failure

Symptoms: the script works for report.txt but fails for my report.txt; a loop treats one filename as two arguments; rm complains about a missing file or removes the wrong thing; an empty variable silently becomes no argument at all.

Likely causes: $file is unquoted; a command substitution is unquoted; the script parses ls output; or a variable is used before it is set. The fix is to quote every expansion: "$file", "$line", "${files[@]}". Read input with IFS= read -r, test with empty strings, spaces, and *, and use bash -x or printf '<%s>\n' "$file" to see where the argument boundaries actually fall.

FAQ

How many techniques should I learn each week?

One or two. At 20–30 minutes a day for five days, that is 100–150 minutes of practice per technique. More than three new ideas in a week usually means none of them become reliable.

Do I need to memorise syntax before writing scripts?

No. Memorise five patterns: variable assignment, if [[ ]], for, while read, and a function definition. Look up the exact test flag or redirection when you need it, then use it in a drill so it sticks.

How do I know I have actually learned a technique?

You can write it from a blank file in under 5 minutes, explain what happens when an input contains spaces or is empty, and repair a deliberately broken version. If you need the example open beside you, repeat the drill.