KKAIROS
Practical guideIllustrative3 min read

Bash variables, loops and if: the basics

Shell variables hold strings; unquoted expansion splits on whitespace; if runs a command and tests its exit status.

Published:

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

TE-36-A: an unquoted variable word-splits; quoting preserves one argument

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

v='a b'; printf 'unquoted=%s\n' $(echo $v | wc -w); printf 'quoted=%s\n' "$v"; set -- $v; echo args=$#; set -- "$v"; echo args_quoted=$#

Recorded output:

unquoted=2
quoted=a b
args=2
args_quoted=1

TE-36-B: a while loop repeats until its test fails, and a for loop walks a list of words

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

n=0; while [ $n -lt 3 ]; do n=$((n+1)); done; echo n=$n; for w in a b c; do printf '%s,' $w; done; echo

Recorded output:

n=3
a,b,c,

Exit status: 0. This status and the output match what was written before the run.

TE-36-C: expected non-zero exit: a numeric test on text that is not a number fails with exit status 2

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

v=abc; [ "$v" -gt 5 ]

Recorded output: none, standard output was empty.

Standard error from the same run:

bash: line 1: [: abc: integer expression expected

Exit status: 2. This status and the output match what was written before the run.

TE-36-B: the while loop stopped when n reached 3, and the for loop printed a, b and c with a comma after each. TE-36-C: by the setup, v is the text abc. The test [ "$v" -gt 5 ] exited with status 2, and bash printed bash: line 1: [: abc: integer expression expected to standard error.

Limits

TE-36-A covers quoting, TE-36-B a while loop and a for loop, and TE-36-C one failing numeric test. Arrays, set -u and changes to IFS are outside this page.

Ad

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-36-A | an unquoted variable word-splits; quoting preserves one argument | 0 | PASS | df12867b0e62 | | TE-36-B | a while loop repeats until its test fails, and a for loop walks a list of words | 0 | PASS | 290906c0a141 | | TE-36-C | expected non-zero exit: a numeric test on text that is not a number fails with exit status 2 | 2 | PASS | 94091b687f1b |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides