Shell Expressions

Shell expressions let you obtain stored values, calculate integer quantities, capture command output, and test relationships. In this lesson, you use Bash syntax to predict the value or status an expression produces. These are separate outcomes: an expression can produce the number zero, while a command can return status zero to report success. Keeping that distinction clear helps you read unfamiliar shell commands accurately.

Expanding values and preserving arguments

An expansion replaces shell notation with a value while Bash prepares a command. Parameter expansion obtains a variable's value; braces make the variable name's boundary explicit. Assignment has no spaces around the equals sign.


Shell
name='Trial One'
printf '%s\n' "${name}_backup"


This prints one line containing Trial One_backup. The single quotes in the assignment preserve literal text. The double quotes in the command allow expansion while keeping its result together. For ordinary scalar parameters, double-quote expansions that should remain one argument.


Without those double quotes, word splitting can turn spaces into argument boundaries. Unquoted results can also undergo filename expansion; pattern syntax is outside this lesson.


Three connected boxes show a double-quoted scalar parameter becoming one command argument.


Parameter expansion can also supply a default. Compare these two forms:


Shell
printf '%s\n' "${name-backup}"
printf '%s\n' "${name:-backup}"


State of name

Without the colon

With the colon

Unset

Uses backup

Uses backup

Set to an empty string

Uses the empty string

Uses backup

Set to nonempty text

Uses that text

Uses that text


Neither form assigns the default to the variable. The colon changes whether an empty value triggers the default.


Command substitution obtains text from a command's standard output:


Shell
count=$(printf '%s\n' 6)


The stored value is 6. Command substitution removes all trailing newline characters, while retaining internal newlines. It captures output, rather than the command's exit status.

Calculating integer values

Arithmetic expansion evaluates an integer expression and substitutes its result. Within the expression, you can reference variables by name. Multiplication and division take precedence over addition and subtraction; parentheses override that order.


Shell
items=17
batch=5
full=$((items / batch))
left=$((items % batch))


Here, full becomes 3 and left becomes 2. For nonnegative item counts and a positive batch size, the governing relationship is


n=bq+r,0≤r<bn=bq+r,\qquad 0\le r<b


Here, nn is the item count, bb the batch size, qq the integer quotient, and rr the remainder. Division truncates toward zero, so this arithmetic does not produce decimal fractions.



Testing relationships and reading status

An exit status is an integer a command returns to report its outcome. Zero indicates success; a nonzero value indicates an unsuccessful outcome. A valid test reports zero when its condition is true and one when false.


Shell
x=12
y=9
[ "$x" -gt "$y" ]
status=$?


The bracketed test compares integers and returns zero because twelve exceeds nine. Spaces separate the brackets and operands. The special parameter in the final assignment obtains the preceding command's status; capture it before another command replaces it.


Use -eq, -gt, and -le for integer equality, greater than, and less than or equal to. In the bracketed test, = compares strings instead. Thus the strings 04 and 4 differ, although they represent equal integers.


Bash also provides an arithmetic command:


Shell
(( 0 ))
status=$?


Unlike arithmetic expansion, this command reports a status: a zero expression gives status one, and a nonzero expression gives status zero. It does not print the calculated value.



What to remember

  • Expansion substitutes values; quoting controls whether ordinary scalar results remain one argument.
  • A colon in the default form makes empty values trigger the fallback too.
  • Arithmetic expansion calculates integers; division truncates toward zero.
  • Command substitution captures output and removes trailing newlines.
  • A successful test returns status zero; an arithmetic value of zero is a different idea.

Example: Preparing a telemetry upload

A telemetry upload contains 26 measurements of 144 bytes each and one 96-byte header. The upload buffer holds 4000 bytes. A separate processing stage handles at most eight measurements per batch. Use arithmetic expansion, which replaces an integer expression with its calculated value, to evaluate the quantities below.


Shell
units=26
per_unit=144
header=96
capacity=4000
batch_size=8


Assume these variables contain the stated decimal integers and that the Bash session continues after commands with nonzero statuses. The header is included once per upload.


a) What total size, in bytes, does this calculation assign to total?


Shell
payload=$((units * per_unit))
total=$((payload + header))


First multiply the number of measurements by the bytes per measurement. The payload size is ________.


P=26(144)=3744 bytesP=26(144)=3744\ \text{bytes}


Next add the single header. Both operands represent byte counts, so their sum is also a byte count.


T=3744+96=3840 bytesT=3744+96=3840\ \text{bytes}


Arithmetic expansion calculates these values before the assignments store them. Ordinary assignment without the arithmetic notation would not itself calculate a sum.


Answer: total is 3840 bytes.


b) What value is assigned to fits_status, and does the upload fit?


Shell
[ "$total" -le "$capacity" ]
fits_status=$?


First compare the required bytes with the buffer capacity. The unused capacity would be ________.


4000−3840=160 bytes4000-3840=160\ \text{bytes}


The integer test asks whether 3840 is less than or equal to 4000. That relationship is true, so the test returns status zero. It does not print the number zero; the following assignment captures its status.


Answer: fits_status is 0, and the upload fits with 160 bytes to spare.


c) How many processing batches are required? Evaluate the expression rather than reporting a decimal quotient.


Shell
batches=$(( (units + batch_size - 1) / batch_size ))


First check the division into complete batches. There are ________ complete batches with ________ remaining.


26=8(3)+226=8(3)+2


The remaining measurements require another batch. The supplied expression implements upward rounding for this positive integer batch size by adding seven before integer division.


batches=26+8−18=338=4in integer arithmetic\text{batches}=\frac{26+8-1}{8}=\frac{33}{8}=4\quad\text{in integer arithmetic}


Check the result: three batches can hold only 24 measurements, while four can hold up to 32. Thus four is the smallest sufficient whole-number batch count.


Answer: 4 processing batches are required.

A Bash session uses its default word-splitting settings and contains the following assignment. Which command passes the variable's complete value as exactly one data argument to printf?


Shell
site='North Lab'
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A Bash upload utility checks text supplied by its user. Complete each sentence with the appropriate string-length operator for the Bash test builtin. Each operator includes its leading hyphen.


For test OPERATOR "upload.csv" to check that the supplied string has at least one character, replace OPERATOR with .


For test OPERATOR "" to check that the supplied string has zero characters, replace OPERATOR with .


These checks concern the supplied text, regardless of whether a file with that name exists.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A Bash program stores 37 records of 80 bytes each, plus one 160-byte header, in blocks of 512 bytes. It evaluates the following expression. What value is assigned to blocks? Answer in blocks, to zero decimal places.


Shell
records=37
bytes_per_record=80
header=160
block_size=512
blocks=$(( (records * bytes_per_record + header + block_size - 1) / block_size ))

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice