Getting Started
Variables
Naming Values
Bash variables hold strings, numbers, paths, and command results. Arithmetic expansion lets a script calculate with integer values.
Program
Play the script to watch named values build a small checkout total step by step.
variables.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash
price=18
quantity=3
subtotal=$((price * quantity))
discount=5
total=$((subtotal - discount))
echo "total=$total"
price ← 18
3price=184quantity=3values this step18pricequantity ← 3
3price=184quantity=35subtotal=$((price * quantity))values this step3quantitysubtotal ← 54
4quantity=35subtotal=$((price * quantity))6discount=5values this step54subtotal18price3quantitydiscount ← 5
5subtotal=$((price * quantity))6discount=57total=$((subtotal - discount))values this step5discounttotal ← 49
6discount=57total=$((subtotal - discount))8echo "total=$total"values this step49total54subtotal5discountecho "total=$total"
7total=$((subtotal - discount))8echo "total=$total"outputtotal=49values this step49total
Follow the Total
pricestarts at18.quantitystarts at3.subtotalis18 * 3, which becomes54.discountis5.totalis54 - 5, so stdout istotal=49. | name | value | | --- | --- | |price| 18 | |quantity| 3 | |subtotal| 54 | |discount| 5 | |total| 49 |
assignment
An assignment stores text in a shell variable with no spaces around `=`.
arithmetic expansion
`$((...))` evaluates integer arithmetic before assignment.
Exercise: variables.sh
Reproduce total=49, then point to the two visible values that make subtotal and the one value subtracted as the discount.