CodeRigor

FREE LESSON

Arguments, quoting & expansion

Preserve argument boundaries, empty values and literal pattern characters when expanding shell data.

Start here; no C++ or other language course is required.

This course runs GNU Bash with ordinary GNU text tools in a fresh Linux sandbox.

A shell command starts as source text and becomes a command name plus an argument vector. Spaces in source separate words, but spaces inside one argument are data. Expansion happens before the command receives that vector. Unquoted parameter expansion can therefore turn a single filename into several arguments, remove an empty argument, or expand a literal star against the current directory. A loop cannot reconstruct the original boundaries afterward.

From source to an argument vector
start / 3
From source to an argument vector

Apply the contract

Single quotes preserve literal text. Double quotes still allow parameter and command substitution, while suppressing word splitting and pathname expansion of those results. Use "$value" for one value and "$@" for the original positional arguments. The latter expands to one word per argument and to no words when there are none. "$*" instead joins arguments into one word using the first IFS character. These forms solve different problems.

One value or many arguments?
start / 3
One value or many arguments?
Bash
values=('two words' '' '*')
printf 'count=%s\n' "${#values[@]}"
for value in "${values[@]}"; do printf '<%s>\n' "$value"; done

Reason about the edge cases

Keep data out of the printf format: printf '%s\n' "$value" uses a constant format and a separate value. A value containing %, backslashes, dollar signs, or shell-looking text stays data. Quoting does not recursively execute a variable's contents. Introducing eval would create a new parsing step and destroy that useful boundary. In the lab, begin with zero arguments, then an empty argument, then a value containing both whitespace and a glob character.

A fixed printf format
start / 3
A fixed printf format

Practice

Write a Bash script that prints count=N and then <VALUE> on its own line for every positional argument, in order. Empty arguments, spaces, newlines, backslashes, leading dashes, percent signs and glob characters are literal data. With no arguments print only count=0. Do not evaluate argument contents as shell code.

Run sample starts again from the first public fixture and grants no mastery evidence. Submit checks all fixtures, including edge cases. Read the specification before editing; the bug and fill phases share the build’s contract. Flashcards reinforce recall on a separate schedule.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Free shell scripting foundation. Use the authored lesson and GNU Bash manual for this lab’s precise argument, status and process contract.