Shell FundamentalsLesson 1.5
Command substitution and arithmetic in Bash
command substitution $(), backtick syntax, arithmetic expansion $(( )), let builtin, bc for floats, expr limitations, integer vs float handling
Command Substitution: Use Output as a Value
Command substitution captures the stdout of a command and injects it as a value. Always use $() — it nests cleanly. Backticks `` ` `` are legacy and don't nest.
today=$(date +%Y-%m-%d)
logfile="app-${today}.log"
echo "Writing to $logfile"
# Nesting works with $()
files=$(ls $(pwd))
# Count lines in a file
lines=$(wc -l < /etc/hosts)
echo "Hosts file has $lines lines"Arithmetic Expansion
Bash handles only integer math natively. Use $(( )) for arithmetic — it's faster than calling external tools.
x=10
y=3
echo $(( x + y )) # 13
echo $(( x * y )) # 30
echo $(( x / y )) # 3 (integer division)
echo $(( x % y )) # 1 (remainder)
# Increment a counter
count=0
(( count++ ))
echo $count # 1Float Math with bc
# Bash can't do floats natively — pipe to bc
result=$(echo "scale=2; 10 / 3" | bc)
echo $result # 3.33
# Percentage calculation
percent=$(echo "scale=1; (42 / 100) * 100" | bc)
echo "${percent}%"For serious numeric work in scripts, awk is faster than repeated bc calls and handles formatted output in one step.
