Command and arithmetic substitution
Capture a command's output with $(...), do integer math with $((...)), and avoid the pitfalls: stripped newlines, padded wc output, no floats, leading zeros.
stdin, stdout and stderrPipes and pipelinesQuoting - single, double and escapesVariables and the environment
Command and arithmetic substitution
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `$(command)` runs the command and is replaced by its standard output with trailing newlines removed. Use it in preference to backticks, because it nests cleanly.
- `$(( expression ))` does integer arithmetic and is replaced by the result. Variables inside it need no `$`.
- Bash arithmetic is integer-only. `7 / 2` is `3`, and `7 / 2.0` is an error. Use `awk` or `bc` for decimals.
- A leading zero means octal, so `$((010))` is `8` and `$((08))` is an error. Strip zeros or write `10#08`.
- On macOS, `wc -l` pads its number with spaces. Capture it with `$(( ))` or `tr -d ' '` before comparing or printing.
Using one command’s output as part of another
Pipes feed one command’s output into another command’s input. That doesn’t help when you want the output inside a command line, such as a filename built from today’s date, or a count you want to print in a sentence. For that, the shell can run a command first and paste its output into the line.
That is command substitution: $(command). Bash runs the command, captures what it writes to standard output, and replaces the whole $(...) with that text. Then the line runs.
$ echo "lines in the log: $(wc -l < logs/access.log)"
lines in the log: 200
Those extra spaces are a macOS detail. BSD wc pads its count, and GNU wc on Linux does not. We’ll come back to it.
The details that matter
Trailing newlines are stripped, but everything else is kept:
$ n=$(printf 'one\n\n\n'); printf '[%s]\n' "$n"
[one]
The older backtick form does the same job, but nesting needs backslashes. Both of these printed outer inner:
$ echo `echo outer \`echo inner\``
outer inner
$ echo "$(echo outer "$(echo inner)")"
outer inner
Use $( ). Quote it like any expansion, as "$(...)", or the output is split on whitespace. The assignment x=$(...) is the one place where quotes are optional.
Failure is visible. An assignment that consists of a substitution returns the substitution’s exit status:
$ v=$(exit 3); echo "assignment status: $?"
assignment status: 3
Inside the substitution, $? works as usual, so $(false; echo "status: $?") printed status inside: 1.
The padded-count trap
On this Mac, the captured count carries leading spaces:
$ n=$(wc -l < logs/access.log); echo "[$n]"
[ 200]
It still works as a number in (( )) and [ -eq ], but it breaks string comparisons and looks wrong in output. Two fixes that I ran: wrap it in arithmetic, n=$(( $(wc -l < file) )), or strip it with tr -d ' '. This is one of the quiet BSD-versus-GNU differences, and a script that is tested only on Linux will not show it.
Arithmetic expansion
$(( expression )) does integer math and is replaced by the result. Variables inside don’t need a $:
$ errors=$(awk '$8 >= 500' logs/access.log | wc -l); echo "5xx: $errors"
5xx: 24
$ total=$(wc -l < logs/access.log); echo "share: $(( errors * 100 / total ))%"
share: 12%
$ x=4; echo $((x * x + 1))
17
The first line counts requests with status 500 or above, using field 8 of the access log, and the second turns it into a percentage. The operators are the C ones: + - * / % **, with parentheses and comparison. Bases work too, and a prefix of 0x means hex:
$ echo $((7 / 2)) $((-7 / 2)) $((7 % 2)) $((2 ** 10))
3 -3 1 1024
$ echo $((0xff)) $((2#1010))
255 10
Division truncates toward zero, so -7 / 2 is -3. As a standalone command, (( ... )) evaluates and sets the exit status, which is useful in conditions: (( x > 3 )) && echo big printed x is big.
Where integer arithmetic stops
No decimals. Bash refuses rather than rounding:
$ echo $((7 / 2.0))
bash: 7 / 2.0: arithmetic syntax error: invalid arithmetic operator (error token is ".0")
For fractions, hand off to awk or bc; both gave 3.50 in my test:
$ awk 'BEGIN { printf "%.2f\n", 7 / 2 }'
3.50
And a leading zero means octal:
$ echo $((010))
8
$ echo $((08))
bash: 08: value too great for base (error token is "08")
This bites when you do arithmetic on zero-padded values such as months, minutes or log fields. Write $((10#08)) to force base 10. I ran this whole set of commands under both Bash 3.2 and 5.3 and diffed the output: the only difference was the wording of the decimal error, which 3.2 prints without the word “arithmetic”. I also ran $((10#08)), which gave 8.
About the video
Script Bit’s “Bash Tutorial Ep. 2 - Shell Expansions, Arithmetic” is 18 minutes 35 seconds and was published in April 2026. I could not read a transcript, but the description has chapters: brace expansion at 0:24, tilde at 3:30, parameter and variable expansion at 4:38, command substitution at 10:30 and arithmetic expansion at 12:40. The embed starts at 10:30 (630 seconds) and plays the last two chapters, which are this lesson’s two topics, to the end of the video. I haven’t checked how deep those eight minutes go, so the padded-wc trap, the octal pitfall and the integer-only limit above come from my own runs, not from the video. It is in English. Learn Linux TV’s six-minute arithmetic video is linked as a second view.
Where this fits
You now know most of the expansions individually. The next lesson ties them together and answers why ls $file split a name apart: word splitting and the order of expansion.
Check yourself
What does `$(date +%F)` become, and why is it better written with `$( )` than with backticks?
It becomes the command's output, for example `2026-11-23`. The `$( )` form nests without escaping and reads clearly, while nested backticks need backslashes.
What is `echo $((7 / 2))`, and how would you get 3.50?
It prints `3`, because Bash does integer arithmetic. For decimals, call `awk 'BEGIN { printf "%.2f\n", 7 / 2 }'` or pipe an expression to `bc -l`.
`count=$(wc -l < file)` then `echo "[$count]"` shows spaces inside the brackets on a Mac. Why, and what fixes it?
BSD `wc` right-aligns its count with padding. Do `count=$(( $(wc -l < file) ))`, which turns the padded number into a plain one, or strip with `tr -d ' '`.
Does `v=$(exit 3); echo $?` print 0 or 3?
It prints 3. An assignment's exit status is that of the last command substitution in it, so you can test a captured command's success.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.