Command Substitution, Chaining, and Exit Codes

How Bash commands report success and failure, how to chain them safely with &&, || and grouping, and how to capture their output with $( ) and xargs.

By The Dark DebuggerUpdated 27 min read

Every command you run returns a number that says whether it worked, and almost every decision a shell script makes is based on that number. This article covers exit codes, chaining commands with ;, && and ||, grouping with braces and subshells, capturing output with command substitution, turning output into arguments with xargs, and two tools for understanding what a command line really runs: type and time. It builds on redirection and pipes; conditionals with if get their full treatment later in your first scripts.

Why exit codes and chaining matter

A cleanup script for a cache directory, written the way many first scripts are:

cd /var/cache/orders-app; rm -rf *

If the directory exists, this does what you expect. If it doesn't (a typo, a different server, a deploy that renamed it), cd fails, the ; runs the next command anyway, and rm -rf * deletes everything in whatever directory you were already in. I replaced rm with echo rm to see what it would have deleted, from a directory holding a deploy script and its config:

cd /var/cache/orders-app; echo rm -rf *
bash: cd: /var/cache/orders-app: No such file or directory
rm -rf access.log app.conf deploy.sh notes.txt

Change one character and the second command only runs if the first succeeded:

cd /var/cache/orders-app && echo rm -rf *
bash: cd: /var/cache/orders-app: No such file or directory

That && works because cd reports failure through its exit status. Everything in this article follows from that one mechanism.

Exit status and $?

When a command finishes, it returns an integer from 0 to 255. 0 means success; any other value means failure. It is the opposite of most programming languages, where 0 is false, so it is worth saying twice: in the shell, zero is success.

The special parameter $? holds the exit status of the most recent command:

ls /etc/hostname
echo $?
ls /etc/nonexistent
echo $?
/etc/hostname
0
ls: cannot access '/etc/nonexistent': No such file or directory
2

Non-zero values are not all the same. Many commands use different codes for different outcomes, and their man pages document them. grep is the one you will use most:

grep -q '^port' app.conf
echo $?
grep -q '^debug' app.conf
echo $?
grep -q '^port' missing.conf
echo $?
0
1
grep: missing.conf: No such file or directory
2

0 means "found a match", 1 means "ran fine, no match", 2 means "something went wrong". grep -q prints nothing and exists purely to produce that status. diff works the same way: 0 for identical files, 1 for different, 2 for trouble. So "non-zero" does not always mean "error"; sometimes it means "no".

The shell itself sets some codes:

nosuchcommand
echo $?
./notes.txt
echo $?
bash: nosuchcommand: command not found
127
bash: ./notes.txt: Permission denied
126

127 is "command not found" and 126 is "found but could not execute" (here, a text file without execute permission). A process killed by a signal reports 128 plus the signal number. SIGTERM is signal 15:

bash -c 'kill -TERM $$'
echo $?
Terminated
143

Exit statuses are stored in 8 bits, so anything above 255 wraps around:

bash -c 'exit 300'
echo $?
44

300 modulo 256 is 44. Keep your own exit codes between 0 and 125 to avoid colliding with the codes the shell reserves.

CodeConventional meaning
0success
1general failure (or "no", e.g. grep found nothing)
2misuse: bad option, missing file (ls, grep, bash builtins)
124the command timed out (set by timeout)
126command found but not executable
127command not found
128+Nkilled by signal N: 130 is Ctrl-C (SIGINT), 141 SIGPIPE, 143 SIGTERM

$? is overwritten by every command

$? reflects the last command, and echo is a command:

ls /etc/nonexistent
echo "status: $?"
echo "status again: $?"
ls: cannot access '/etc/nonexistent': No such file or directory
status: 2
status again: 0

The second echo reports the status of the first echo. If you need the value more than once, save it immediately: status=$?.

true, false, and !

true does nothing and returns 0; false does nothing and returns 1. They are useful as placeholders and in examples, and while true is the standard infinite loop:

true
echo $?
false
echo $?
0
1

! in front of a command (or pipeline) inverts its status: 0 becomes 1 and any non-zero becomes 0.

! grep -q '^debug' app.conf
echo $?
0

grep found no debug line (status 1), so the negated status is 0, "true". You'll see if ! command; then in nearly every script.

Chaining commands: ;, &&, ||

Three operators join commands on one line, and they differ only in when the second command runs:

OperatorRuns the next commandExample
a ; balwaysmake clean; make
a && bonly if a succeeded (status 0)mkdir build && cd build
a || bonly if a failed (status non-zero)cd "$dir" || exit 1
false; echo "this runs anyway"
false && echo "this is skipped"
false || echo "this runs because false failed"
this runs anyway
this runs because false failed

Combined with grep -q, they read almost like English:

grep -q '^max_connections' app.conf && echo "max_connections is set"
grep -q '^debug' app.conf || echo "debug not set, using default (false)"
max_connections is set
debug not set, using default (false)

In scripts, || is the idiom for "or stop here". These two lines appear in some form at the top of countless scripts:

cd "$deploy_dir" || exit 1
command -v rsync > /dev/null || { echo "rsync is required" >&2; exit 1; }

My rule of thumb: never write cd somewhere; something in a script. Use cd somewhere && something, or cd somewhere || exit 1 on its own line.

a && b || c is not if/else

This pattern looks like a compact if/else:

[[ -f app.conf ]] && grep -q '^debug = true' app.conf && echo "debug mode ON" || echo "app.conf not found"
app.conf not found

But app.conf exists. What happened: && and || have equal precedence and are evaluated left to right. The [[ -f ]] test succeeded, grep found no debug = true line and returned 1, and because the chain so far had failed, || ran the "else" branch. c runs if either a or b fails, not only when a fails.

The failure can come from a place you'd never suspect. Here b is an echo that can't write its output (/dev/full is a Linux device that always reports "disk full"):

true && echo "deployed" > /dev/full || echo "deploy FAILED"
bash: echo: write error: No space left on device
deploy FAILED

The deploy (true) succeeded, and the script reported failure anyway. When the branches matter, write the if:

if [[ ! -f app.conf ]]; then echo "app.conf not found"; elif grep -q '^debug = true' app.conf; then echo "debug mode ON"; else echo "debug mode off"; fi
debug mode off

a && b || c is fine when b cannot fail (like echo to a terminal) and you accept the edge case. For anything that decides what a script does next, use if. Your first scripts covers if, [[ ]] and elif properly.

Grouping commands: { } and ( )

Both group several commands so you can redirect them together or chain them as a unit. The difference is where they run.

Parentheses run the commands in a subshell: a child copy of the shell. Changes to variables, the current directory, or shell options vanish when it exits:

cd /var
(cd /etc && pwd)
pwd
/etc
/var
x=1; (x=2; echo "inside: $x"); echo "outside: $x"
inside: 2
outside: 1

Braces run the commands in the current shell, so changes stick:

x=1; { x=2; echo "inside: $x"; }; echo "outside: $x"
inside: 2
outside: 2

$BASH_SUBSHELL shows how deep you are:

echo "$BASH_SUBSHELL"; (echo "$BASH_SUBSHELL"; (echo "$BASH_SUBSHELL"))
0
1
2

Use parentheses when you want isolation: (cd build && make) builds in another directory without moving your script. Use braces to treat several commands as one for redirection or chaining, without paying for a new process:

{ date +%F; uname -sr; } > status.txt
cat status.txt
2026-11-09
Linux 6.18.54.1-microsoft-standard-WSL2

Brace syntax is strict because { and } are reserved words, not operators. You need a space after {, and a ; or newline before }:

{echo hi}
bash: {echo: command not found

Bash read {echo as a command name. The missing-semicolon version fails differently; it is in Common mistakes.

Command substitution: $( )

$(command) runs a command and replaces itself with the command's output. It is how you get the output of one command into a variable or into the arguments of another:

today=$(date +%F)
echo "$today"
echo "Running kernel $(uname -r) as $(id -un)"
backup="orders-db-$(date +%Y%m%d).sql.gz"
echo "$backup"
2026-11-09
Running kernel 6.18.54.1-microsoft-standard-WSL2 as sid
orders-db-20261109.sql.gz

Trailing newlines are removed

Command substitution strips all trailing newlines from the output (and only trailing ones):

out=$(printf 'line1\nline2\n\n\n')
echo "[$out]"
[line1
line2]

This is why count=$(wc -l < file) gives you a clean number. It also means you can't use $( ) to capture output where trailing blank lines matter.

Quote it

An unquoted $( ) goes through word splitting and globbing, exactly like an unquoted variable (see variables and quoting). Multi-line output collapses onto one line:

hits=$(grep ' 404 ' access.log | cut -d' ' -f7 | sort -u | head -n 3)
echo $hits
echo "$hits"
/.env /.git/config /admin/config.php
/.env
/.git/config
/admin/config.php

And output that looks like a wildcard gets expanded against the files in your directory:

pattern=$(echo '*.pdf')
echo $pattern
echo "$pattern"
invoice.pdf q3 report.pdf
*.pdf

The classic bug is looping over $(ls). A file named q3 report.pdf becomes two "files":

for f in $(ls *.pdf); do echo "file: $f"; done
file: invoice.pdf
file: q3
file: report.pdf

The glob alone does it correctly, because glob results are never split:

for f in *.pdf; do echo "file: $f"; done
file: invoice.pdf
file: q3 report.pdf

Rule: write "$(...)" with double quotes unless you have a specific reason not to. The one common exception is the right-hand side of an assignment (var=$(cmd)), where no splitting happens, so quotes there are optional.

Nesting, and why backticks lost

$( ) nests cleanly, and quotes inside it are independent of quotes outside it:

echo "$(basename "$(dirname /var/log/nginx/access.log)")"
nginx

The older backtick form `command` does the same job, but nesting needs escaped backticks:

echo `basename \`dirname /var/log/nginx/access.log\``
nginx

Backslashes also behave differently inside backticks, which produces genuinely surprising results:

echo $(echo \$HOME)
echo `echo \$HOME`
$HOME
/home/sid

Inside backticks, \$ is unescaped before the inner command runs, so the inner echo sees $HOME and expands it. Use $( ) in everything you write. You need to recognise backticks only because old scripts and Stack Overflow answers are full of them.

Command substitution runs in a subshell

Assignments inside $( ) don't affect the outer shell:

x=1; y=$(x=2; echo "$x"); echo "x=$x y=$y"
x=1 y=2

Its exit status is kept

An assignment like var=$(cmd) has the exit status of cmd, so you can capture output and test for success in one step:

if count=$(grep -c ' 500 ' access.log); then echo "found $count server errors"; fi
if count=$(grep -c ' 503 ' access.log); then echo "found $count"; else echo "no 503s (grep exit $?), count=$count"; fi
found 1 server errors
no 503s (grep exit 1), count=0

There is one important exception, local var=$(cmd), which is in Common mistakes.

Reading a file: $(< file)

$(< file) is a Bash shortcut for $(cat file) that reads the file directly instead of starting cat:

printf '%s\n' web01 web02 db01 > hosts.txt
hosts=$(< hosts.txt)
echo "$hosts"
web01
web02
db01

Every substitution costs a process

$( ) forks a subshell each time. That is invisible for one call and very visible in a loop. 1,000 iterations, with and without a substitution:

time for i in {1..1000}; do v=$(echo hi); done
time for i in {1..1000}; do v=hi; done
 
real	0m2.058s
user	0m0.508s
sys	0m1.147s
 
real	0m0.004s
user	0m0.000s
sys	0m0.003s

Two seconds versus four milliseconds. If a loop over thousands of lines is slow, look for $( ) inside it; often a single awk program over the whole file does the job instead (see awk).

xargs: turning output into arguments

Pipes connect stdout to stdin. But many commands ignore stdin and only act on their arguments: rm, cp, mkdir, kill. Piping a list of files into rm doesn't work:

ls cache/*.tmp | rm
rm: missing operand
Try 'rm --help' for more information.

xargs reads items from stdin and appends them as arguments to a command:

ls cache/*.tmp | xargs rm -v
removed 'cache/session-1.tmp'
removed 'cache/session-2.tmp'
removed 'cache/session-3.tmp'

-t prints each command line before running it, which is the best way to see what xargs builds. By default it packs as many arguments into one command as it can; -n 1 runs the command once per item:

printf '%s\n' app.conf access.log hosts.txt | xargs -t wc -l
wc -l app.conf access.log hosts.txt
  23 app.conf
  33 access.log
   3 hosts.txt
  59 total
printf '%s\n' app.conf access.log hosts.txt | xargs -t -n 1 wc -l
wc -l app.conf
23 app.conf
wc -l access.log
33 access.log
wc -l hosts.txt
3 hosts.txt

-I{} runs the command once per input line and substitutes the line wherever {} appears, which you need when the item isn't the last argument. This stages one config file per host:

xargs -I{} cp app.conf staging/{}.conf < hosts.txt
ls staging
db01.conf
web01.conf
web02.conf

Spaces in names, and empty input

xargs splits its input on whitespace by default, so a filename with a space breaks the same way $(ls) did:

touch "cache/q3 export.tmp" cache/daily.tmp
ls cache/*.tmp | xargs rm -v
removed 'cache/daily.tmp'
rm: cannot remove 'cache/q3': No such file or directory
rm: cannot remove 'export.tmp': No such file or directory

The robust fix is to separate items with a NUL byte, which can't appear in a filename: find -print0 produces that format and xargs -0 reads it.

find cache -name '*.tmp' -print0 | xargs -0 rm -v
removed 'cache/q3 export.tmp'

And when there is no input at all, GNU xargs still runs the command once, with no arguments. -r (--no-run-if-empty) prevents that:

find cache -name '*.tmp' | xargs rm
find cache -name '*.tmp' | xargs -r rm
echo "exit: $?"
rm: missing operand
Try 'rm --help' for more information.
exit: 0

Running jobs in parallel with -P

-P N runs up to N commands at once. Six one-second jobs, one at a time and then three at a time:

time (seq 1 6 | xargs -I{} sh -c 'sleep 1; echo "job {} done"')
job 1 done
job 2 done
job 3 done
job 4 done
job 5 done
job 6 done
 
real	0m6.048s
user	0m0.017s
sys	0m0.004s
time (seq 1 6 | xargs -P 3 -I{} sh -c 'sleep 1; echo "job {} done"')
job 1 done
job 3 done
job 2 done
job 4 done
job 5 done
job 6 done
 
real	0m2.034s
user	0m0.011s
sys	0m0.012s

Note the order: parallel jobs finish in whatever order they finish. find, -exec versus xargs, and more -print0 patterns are covered in finding files.

What will actually run? type, command, builtin

A command name can be an alias, a shell keyword, a function, a builtin or a program on disk, and Bash checks them in that order. type tells you which one you'll get:

type ls cd echo time grep
ls is /usr/bin/ls
cd is a shell builtin
echo is a shell builtin
time is a shell keyword
grep is /usr/bin/grep

type -a lists every match, which is how you discover that echo exists both inside Bash and as a program:

type -a echo
echo is a shell builtin
echo is /usr/bin/echo
echo is /bin/echo

type -t prints a single word (alias, function, builtin, keyword, file), which is handy in scripts. Aliases and functions show up too:

alias ll='ls -l'
type ll
ll is aliased to `ls -l'

command -v is the portable way to ask "does this command exist?" It prints the path (or the name, for builtins) and returns 1 if nothing is found:

command -v grep
command -v cd
command -v nosuchtool
echo $?
/usr/bin/grep
cd
1

Prefer command -v over which. which is an external program that only searches PATH, so it knows nothing about builtins, functions or aliases (which cd prints nothing and fails), and its behaviour varies between systems.

command name (without -v) runs name while skipping functions and aliases, and builtin name runs only the builtin. Both matter when you wrap a command in a function of the same name:

ls() { echo "my ls function was called"; }
ls -d /etc
command ls -d /etc
unset -f ls
my ls function was called
/etc
cd() { builtin cd "$@" && echo "now in: $PWD"; }
cd /etc
unset -f cd
now in: /etc

Without builtin, the cd inside the function would call the function again, forever.

Timing commands with time

time is a shell keyword that runs a command or pipeline and reports three numbers:

time sleep 1
 
real	0m1.002s
user	0m0.002s
sys	0m0.001s
  • real: wall-clock time from start to finish.
  • user: CPU time spent running the program's own code.
  • sys: CPU time spent in the kernel on the program's behalf (file I/O, process creation).

sleep uses almost no CPU, so real is high and user and sys are near zero. A CPU-heavy job looks different. Sorting two million shuffled numbers:

seq 1 2000000 | sort -R > nums.txt
time sort -n nums.txt > /dev/null
 
real	0m1.647s
user	0m5.142s
sys	0m0.814s

user is larger than real. GNU sort uses several threads on large inputs, and user time adds up CPU time across all of them. A big gap like this tells you a command is running in parallel; real much larger than user plus sys tells you it's waiting (on disk, network or sleep).

Because time is a keyword rather than a program, it times a whole pipeline:

time seq 1 2000000 | sort -rn | head -n 1
2000000
 
real	0m1.374s
user	0m1.224s
sys	0m0.077s

The TIMEFORMAT variable controls the output; %R is real seconds:

TIMEFORMAT='elapsed: %Rs'
time sleep 0.5
unset TIMEFORMAT
elapsed: 0.502s

There is also a separate GNU time program (type -a time shows it at /usr/bin/time). Call it by full path when you want more than timings; -v adds peak memory use, page faults and context switches. It prints to stderr, so > /dev/null only discards the sorted numbers:

/usr/bin/time -v sort -n nums.txt > /dev/null
	Command being timed: "sort -n nums.txt"
	User time (seconds): 5.84
	System time (seconds): 1.91
	Percent of CPU this job got: 233%
	Elapsed (wall clock) time (h:mm:ss or m:ss): 0:03.33
[…]
	Maximum resident set size (kbytes): 267656
[…]
	Exit status: 0

"Maximum resident set size" is the peak RAM the process used: about 260 MiB to sort two million lines. That number is what you check before running a job on a small VM or a container with a memory limit.

Where you'll use this

Exit codes and chaining are how shell scripts make decisions:

  • Deploy and CI scripts chain steps with && so nothing runs after a failed step, and CI systems mark a job red purely on a non-zero exit code. Jenkins, GitHub Actions and GitLab all work this way.
  • Guard clauses at the top of scripts: command -v jq > /dev/null || die "jq required".
  • Command substitution builds names and values: timestamped backup files, the current git commit in a release name, the count of errors in a log.
  • xargs turns search results into batch operations: delete what find found, run a check against every host in a list, process files in parallel.

Here is a complete pre-deployment check that uses all of it. It exits 0 with one summary line, or exits 1 with a reason on stderr, so a pipeline can run ./preflight.sh && ./deploy.sh:

#!/usr/bin/env bash
# preflight.sh - checks to run before deploying the order service.
# Prints one OK line, or a FAIL line on stderr and exits 1.
set -o pipefail
 
die() { echo "preflight: FAIL: $*" >&2; exit 1; }
 
conf=${1:-./app.conf}
 
# Required tools must be installed.
for tool in tar gzip curl; do
    command -v "$tool" > /dev/null || die "required command not found: $tool"
done
 
# The config must be readable and contain a port setting.
[[ -r $conf ]] || die "cannot read $conf"
port=$(grep -m 1 '^port' "$conf" | cut -d= -f2 | tr -d ' ') || die "no port setting in $conf"
 
# At least 1 GiB free where the release will be unpacked (df reports KiB).
avail_kb=$(df --output=avail -k . | tail -n 1 | tr -d ' ')
[[ $avail_kb -ge 1048576 ]] || die "only $avail_kb KiB free in $PWD"
 
release="orders-$(date +%Y%m%d-%H%M)-$(id -un)"
echo "preflight: OK port=$port free=$(( avail_kb / 1024 ))MiB release=$release"

Three runs: a good config, a missing file, and a config with the port line removed (grep -v '^port' app.conf > noport.conf):

./preflight.sh
echo "exit: $?"
./preflight.sh missing.conf
echo "exit: $?"
./preflight.sh noport.conf
echo "exit: $?"
preflight: OK port=8080 free=3880MiB release=orders-20261109-2136-sid
exit: 0
preflight: FAIL: cannot read missing.conf
exit: 1
preflight: FAIL: no port setting in noport.conf
exit: 1

The port=$(...) || die line is worth a second look. Without set -o pipefail, the pipeline's status would be that of tr, which succeeds on empty input, and the script would carry on with an empty port. With pipefail, grep finding nothing fails the whole substitution and die runs. Chained with the deploy step:

./preflight.sh && ./deploy.sh
./preflight.sh noport.conf && ./deploy.sh
preflight: OK port=8080 free=3880MiB release=orders-20261109-2136-sid
deploying
preflight: FAIL: no port setting in noport.conf

The for loop and [[ ]] tests used here are covered in loops and functions and your first scripts.

Common mistakes

local var=$(cmd) hides the failure

Inside a function, declaring and assigning in one statement throws away the substitution's exit status:

f() { local out=$(grep -c ' 503 ' access.log); echo "status: $?"; }
f
g() { local out; out=$(grep -c ' 503 ' access.log); echo "status: $?"; }
g
status: 0
status: 1

In f, $? is the status of local itself, which succeeded. Declare first, assign on a separate line, as in g. The same applies to export var=$(cmd) and readonly var=$(cmd). ShellCheck flags this as SC2155.

Exiting from a subshell doesn't exit the script

cat safe-cd.sh
#!/usr/bin/env bash
cd releases/current || (echo "cannot cd to releases/current" >&2; exit 1)
echo "still running - this line should never print"
bash safe-cd.sh
echo "exit: $?"
safe-cd.sh: line 2: cd: releases/current: No such file or directory
cannot cd to releases/current
still running - this line should never print
exit: 0

The exit 1 ran inside the parentheses, so it ended only the subshell. Use braces, which run in the current shell:

cd releases/current || { echo "cannot cd to releases/current" >&2; exit 1; }

With that one change, the script stops after the error message and exits with 1.

A brace group without the final semicolon

cat brace.sh
bash brace.sh
#!/usr/bin/env bash
{ echo "checking"; echo "done" }
brace.sh: line 3: syntax error: unexpected end of file

Without ; before it, } is just an argument to the second echo, so Bash never sees the group close and reaches the end of the file still looking for it. Write { echo "checking"; echo "done"; }.

Testing $? after something else ran

grep -q '^debug' app.conf
echo "checking result..."
if [ $? -ne 0 ]; then echo "no debug line"; fi
checking result...

app.conf has no debug line, yet nothing was reported: the if tested the status of echo, which is 0. Test the command directly, which is clearer anyway, or save status=$? on the very next line:

if ! grep -q '^debug' app.conf; then echo "no debug line"; fi
no debug line

Summary

  • Every command returns an exit status: 0 is success, 1 to 255 is failure. $? holds the last one and is overwritten by every command, including echo.
  • Know the special codes: 1 for general failure or "no match", 2 for misuse, 126 not executable, 127 not found, 128+N killed by signal N.
  • ; always continues, && continues on success, || continues on failure. Use cmd || exit 1 (or || { ...; exit 1; }) as a guard; never cd dir; rm ....
  • a && b || c runs c when either a or b fails. Use if/else when the branches matter.
  • ( ) runs commands in a subshell, so cd, variables and exit don't escape; { ...; } runs them in the current shell and needs spaces and a closing ;.
  • "$( )" captures output with trailing newlines removed; always quote it, prefer it over backticks, and remember local var=$(cmd) loses the exit status.
  • xargs turns stdin into arguments: -n 1 one item per command, -I{} placement, -0 with find -print0 for safe filenames, -r for empty input, -P for parallelism.
  • type shows what a name really is, command -v checks if it exists, and time measures real, user and sys time for a whole pipeline.

Exercises

Exercise 1: Predict the exit codeseasy

Before running each line, write down the number you expect echo $? to print. Then run them. (staging/web01.conf and staging/db01.conf are identical copies of app.conf from the xargs section.) Finally, use type to find out what [, [[ and test are.

grep -q sid /etc/passwd; echo $?
grep -q nosuchuser /etc/passwd; echo $?
diff staging/web01.conf staging/db01.conf > /dev/null; echo $?
diff staging/web01.conf hosts.txt > /dev/null; echo $?
bash -c 'exit 256'; echo $?
Show Solution
0
1
0
1
0

grep returns 0 for a match and 1 for no match. diff returns 0 for identical files and 1 for different ones. 256 wraps around to 0, so exit 256 reports success, a good reason to keep your own codes small.

type [ [[ test
[ is a shell builtin
[[ is a shell keyword
test is a shell builtin

[ is a command (a builtin version of test), which is why it needs spaces around its arguments. [[ is a keyword that Bash parses specially, which is why it can do things [ can't.

Exercise 2: Fix a misleading one-linermedium

This line is supposed to say whether the [metrics] section is enabled, or that the file is missing:

[[ -f $f ]] && grep -q '^enabled = true' "$f" && echo "metrics enabled" || echo "$f is missing"

Create a copy of the config with metrics turned off (sed 's/^enabled = true/enabled = false/' app.conf > metrics-off.conf), run the line with f=metrics-off.conf, and explain the output. Then rewrite it with if/elif/else and test it with metrics-off.conf, app.conf and a file that doesn't exist.

Show Solution
f=metrics-off.conf
[[ -f $f ]] && grep -q '^enabled = true' "$f" && echo "metrics enabled" || echo "$f is missing"
metrics-off.conf is missing

The file exists, but grep failed, and || runs when anything before it failed.

f=metrics-off.conf
if [[ ! -f $f ]]; then echo "$f is missing"; elif grep -q '^enabled = true' "$f"; then echo "metrics enabled"; else echo "metrics disabled"; fi
f=app.conf
if [[ ! -f $f ]]; then echo "$f is missing"; elif grep -q '^enabled = true' "$f"; then echo "metrics enabled"; else echo "metrics disabled"; fi
f=nope.conf
if [[ ! -f $f ]]; then echo "$f is missing"; elif grep -q '^enabled = true' "$f"; then echo "metrics enabled"; else echo "metrics disabled"; fi
metrics disabled
metrics enabled
nope.conf is missing

Three outcomes need three branches; &&/|| can only express two.

Exercise 3: Build an archive namemedium

Inside a directory called orders-service, set a variable archive to <directory name>-<YYYYMMDD>.tar.gz using command substitution only (no typing the directory name). Print it.

Hint

$PWD holds the full path; basename strips everything up to the last /. You need two substitutions, one of them nested in quotes.

Show Solution
mkdir -p orders-service && cd orders-service
archive="$(basename "$PWD")-$(date +%Y%m%d).tar.gz"
echo "$archive"
orders-service-20261109.tar.gz

The inner "$PWD" is quoted so a directory name with spaces still works; quotes inside $( ) don't interfere with the quotes around the whole value.

Exercise 4: Parallelise a slow batchhard

Six jobs each take one second; simulate them with sh -c 'sleep 1; echo "job N done"'. Use seq and xargs to run all six one at a time and time it, then run them three at a time. Explain the difference in real time and why the output order changes.

Show Solution
time (seq 1 6 | xargs -I{} sh -c 'sleep 1; echo "job {} done"')
job 1 done
job 2 done
job 3 done
job 4 done
job 5 done
job 6 done
 
real	0m6.048s
user	0m0.017s
sys	0m0.004s
time (seq 1 6 | xargs -P 3 -I{} sh -c 'sleep 1; echo "job {} done"')
job 1 done
job 3 done
job 2 done
job 4 done
job 5 done
job 6 done
 
real	0m2.034s
user	0m0.011s
sys	0m0.012s

Six seconds sequentially, two seconds with three workers: two "rounds" of three one-second jobs. CPU time barely changes because the jobs are just waiting. Jobs that run at the same time finish in an unpredictable order, so the output is shuffled within each round. If the order matters, have each job write its own output file, or sort the combined output afterwards.


Tested with: GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), November 2026, with GNU findutils xargs and coreutils. Every command was run as shown in an interactive shell and the output pasted unchanged; timings will differ on your machine, but the ratios shouldn't. One run of the sequential xargs timing came out at 4.3 seconds, which is impossible for six one-second sleeps; it was a clock glitch in the VM, and a re-run gave the 6.0 seconds shown. The /usr/bin/time -v output is from a separate run and was trimmed with […].

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Bash tutorial here is tested end to end before publishing.