Bash / Basic: syntax, values, and control / Lesson 7
Build a predictable command-line argument contract
Validate positional argument counts and preserve exact argument boundaries through a small Bash interface.
On this page
Lesson goals
- Distinguish argument count from argument content.
- Pass values without splitting or glob expansion.
- Report usage errors separately from successful output.
- Validate argument counts and content as separate rules.
- Preserve exact boundaries and test status, stdout and stderr independently.
Define what the command accepts
A command-line interface receives an ordered list of arguments, not a single sentence. Before writing the function, decide how many arguments are required, whether an empty string is valid, and which exit statuses indicate invalid usage. The example accepts exactly one value, including an empty value. It writes the result to standard output and the usage message to standard error so a caller can distinguish data from diagnostics.
Check count before reading
The function checks $# before accessing $1. Its numeric comparison tests the number of arguments, while quoting "$1" preserves the supplied value as one argument to printf. Calling show_arg with a quoted phrase therefore prints one value rather than two. A real program may also need to validate the value itself; a correct argument count does not prove that a path exists or that a number is within range.
show_arg() {
if (( $# != 1 )); then
printf "usage: show_arg VALUE\n" >&2
return 2
fi
printf "value=<%s>\n" "$1"
}
show_arg "two words"
The count guard returns a usage error; the quoted value remains one printf argument.
Preserve a list as an array
An array stores each element separately, including an empty element and a literal wildcard. Quoted "${args[@]}" expands to one argument per element, while the length expression reports the number of elements. The example uses printf rather than echo so the output format is explicit. Treat the examples as separate Bash snippets; the second does not depend on the function in the first.
args=("two words" "*.txt" "")
printf "count=%s\n" "${#args[@]}"
printf "value=<%s>\n" "${args[@]}"
The array retains three elements, including a literal wildcard and an empty string.
Keep data away from shell syntax
Passing an argument directly does not require building a command string and evaluating it. Use arrays for a variable list of arguments, and quote expansions when passing them to a command. Quoting preserves boundaries but does not prevent a target command from treating a leading dash as an option. For path operands use -- where that particular command supports it, and validate any additional domain requirements.
Verify the public behavior
Test no arguments, one ordinary value, one value with spaces, an empty value, a wildcard, and two arguments. Assert exit status, standard output, and standard error separately. Run the test in a temporary directory containing a filename that matches the wildcard to expose accidental globbing. Verify that rejected input does not trigger a side effect; this example prints only and does not modify files.
Define the argument contract
A command-line interface receives an ordered argument list, not one sentence. Decide how many arguments are required, whether an empty value is valid, and what status represents invalid usage before implementing the parser. For example, a display helper can require exactly one argument while accepting the empty string as a legitimate value. A missing argument and a present empty argument have different counts even if both might print as blank.
Document which output goes to standard output and which diagnostics go to standard error. A caller capturing successful data should not receive the usage message as if it were a value. Return a nonzero usage status when the count is invalid, and ensure validation happens before any side effect. A correct count alone does not validate the domain of a path, number or identifier.
Check count and content separately
The special parameter $# reports the number of positional arguments. Check it before reading required positions such as $1, particularly when nounset may be enabled. If the contract accepts exactly one value, both zero and two arguments should follow the usage-error path. An explicitly empty first argument still counts as one; if empty is forbidden, test that rule separately after the count check.
Quote "$1" when passing it to another command so spaces and wildcard characters stay within one argument. Use a fixed printf format and pass the value as data. A phrase like "two words" is one argument when quoted in the caller, while two separately supplied words are two arguments. Validate the actual content separately for domain rules such as numeric range or authorized paths.
Preserve a structured list
A Bash array stores each intended argument as an element, including spaces, a literal wildcard and an empty string. Quoted "${args[@]}" expands the elements as separate arguments; joining them into a scalar loses the original boundaries. Quoted "$@" preserves an existing positional list when forwarding it through a helper. Inspect the receiving function’s argument count and each value rather than guessing from a rendered command line.
For the synthetic array ("two words" "*.txt" ""), the receiver gets three arguments. The asterisk remains data when the expansion is quoted, even if a matching file exists in the working directory. Arrays are Bash syntax, so document and select Bash for a script that uses them. Do not use eval to reconstruct a command from data that already has structured boundaries.
Separate option interpretation from quoting
Quoting keeps a leading-dash value such as -x in one argument, but it does not force the receiving utility to treat that argument as an operand. Consult the utility’s documented interface. Where supported, place -- before operands to end option parsing, or use an appropriate explicit pathname such as ./-x. Not every command accepts the same conventions, so the interface is part of the contract.
Quoting also does not establish that a path is inside an authorized directory, that a number is within range, or that a filename exists. Apply those rules at the relevant boundary after preserving the argument. Keep command selection fixed or explicitly validated, use fixed output formats, and avoid introducing a second shell parse merely to pass user data.
Test status and streams independently
Exercise zero arguments, one ordinary value, one value with spaces, one empty value, a literal wildcard and two arguments. For each invocation assert the exit status, standard output and standard error separately. A usage error should not be mistaken for successful output simply because a diagnostic was printed. Verify that rejected input causes no side effect before the guard returns.
Use an isolated temporary working directory with a synthetic filename matching the wildcard to expose accidental filename expansion. Remove the fixture afterward and avoid inspecting or changing unrelated files. Test the exact public behavior, including the documented policy for an empty argument and a leading dash. A bounded test should not depend on the learner’s home directory, personal aliases or ambient filenames.
20 worked examples
1. Accept one spaced argument
Problem: Pass a quoted phrase to a one-argument helper.
- The caller quotes the phrase, so the function receives exactly one positional argument.
- A quoted phrase crosses the call boundary as one word, so the exact-count guard accepts it without splitting the space.
show() { if (( $# != 1 )); then return 2; fi; printf "<%s>\n" "$1"; }
show "two words"
<two words>
Why this result follows: The caller quotes the phrase, so the function receives exactly one positional argument.
2. Accept one empty argument
Problem: Pass an explicitly empty value to a helper that permits it.
- The quoted empty string is one argument even though its contents have zero length.
- The explicit empty string occupies one position, so the exact-one guard must not confuse it with a missing argument.
show() { if (( $# != 1 )); then return 2; fi; printf "<%s>\n" "$1"; }
show ""
<>
Why this result follows: The quoted empty string is one argument even though its contents have zero length.
3. Reject a missing argument
Problem: Return a usage status when the caller supplies no value.
- The function receives zero arguments, so its count guard returns status two before accessing $1.
- The zero count fails the guard before $1 is read, and the caller receives the documented usage status.
show() { if (( $# != 1 )); then return 2; fi; printf "%s\n" "$1"; }
if show; then printf "ok\n"; else status=$?; printf "status=%s\n" "$status"; fi
status=2
Why this result follows: The function receives zero arguments, so its count guard returns status two before accessing $1.
4. Reject two arguments
Problem: Return a usage status when exactly one value is required.
- The two supplied values make $# equal two, violating the exact-one contract.
- Two separately supplied words make the count two, so neither value reaches the successful display branch.
show() { if (( $# != 1 )); then return 2; fi; printf "%s\n" "$1"; }
if show one two; then printf "ok\n"; else status=$?; printf "status=%s\n" "$status"; fi
status=2
Why this result follows: The two supplied values make $# equal two, violating the exact-one contract.
5. Preserve a literal wildcard
Problem: Pass an asterisk-containing value as one quoted argument.
- The quoted expansion prevents the wildcard from matching filenames.
- The quoted expansion protects *.txt from filename matching, so the receiver gets the pattern itself.
show() { printf "<%s>\n" "$1"; }
value="*.txt"
show "$value"
<*.txt>
Why this result follows: The quoted expansion prevents the wildcard from matching filenames.
6. Count a structured array
Problem: Pass a phrase, wildcard and empty element to a receiver.
- Quoted array-at expansion supplies each of the three elements separately.
- Quoted array-at expansion passes three elements, preserving the phrase, literal pattern and empty final value.
args=("two words" "*.txt" "")
show() { printf "%s\n" "$#"; printf "<%s>\n" "$@"; }
show "${args[@]}"
3
<two words>
<*.txt>
<>
Why this result follows: Quoted array-at expansion supplies each of the three elements separately.
7. Forward a positional list
Problem: Forward a spaced value and an empty value through a helper.
- Quoted "$@" preserves the two function arguments when forwarding them.
- Quoted positional-at forwarding keeps the spaced first argument and empty second argument distinct.
receive() { printf "%s|<%s>|<%s>\n" "$#" "$1" "$2"; }
forward() { receive "$@"; }
forward "red apple" ""
2|<red apple>|<>
Why this result follows: Quoted "$@" preserves the two function arguments when forwarding them.
8. Separate usage diagnostics
Problem: Send a usage message to standard error and return two.
- The missing argument triggers a diagnostic on standard error and a nonzero return.
- The count guard writes its diagnostic to stderr and returns two, so suppressing that stream does not turn failure into success.
show() { if (( $# != 1 )); then printf "usage\n" >&2; return 2; fi; printf "%s\n" "$1"; }
if show 2>/dev/null; then printf "ok\n"; else status=$?; printf "status=%s\n" "$status"; fi
status=2
Why this result follows: The missing argument triggers a diagnostic on standard error and a nonzero return.
9. Observe a successful status
Problem: Capture the status after displaying one ordinary value.
- One argument satisfies the guard and the successful printf returns zero.
- One ordinary argument passes the guard and successful printf supplies status zero, which the caller captures immediately.
show() { if (( $# != 1 )); then return 2; fi; printf "%s\n" "$1"; }
show hello
status=$?
printf "status=%s\n" "$status"
hello
status=0
Why this result follows: One argument satisfies the guard and the successful printf returns zero.
10. Reject empty content explicitly
Problem: Require one nonempty argument rather than count alone.
- The quoted empty argument satisfies the count but fails the separate nonempty test.
- The count succeeds for one empty argument but the independent nonempty test rejects its contents.
show() { if (( $# != 1 )) || [[ -z $1 ]]; then return 2; fi; printf "%s\n" "$1"; }
if show ""; then printf "ok\n"; else printf "rejected\n"; fi
rejected
Why this result follows: The quoted empty argument satisfies the count but fails the separate nonempty test.
11. Accept empty content explicitly
Problem: Distinguish an empty value from a missing argument by count.
- The exact-count condition is satisfied because the caller supplied one argument.
- The explicitly empty argument counts as one and is accepted because this particular contract permits empty content.
show() { if (( $# != 1 )); then return 2; fi; printf "count=%s value=<%s>\n" "$#" "$1"; }
show ""
count=1 value=<>
Why this result follows: The exact-count condition is satisfied because the caller supplied one argument.
12. Avoid a side effect on rejection
Problem: Check the count before changing a caller variable.
- The zero-argument call fails the guard before the assignment to changed.
- The zero-argument guard returns before changed=yes, so the parent retains the original no flag.
changed=no
show() { if (( $# != 1 )); then return 2; fi; changed=yes; }
show || :
printf "%s\n" "$changed"
no
Why this result follows: The zero-argument call fails the guard before the assignment to changed.
13. Preserve a dash-leading value
Problem: Show the exact argument a receiver obtains for -x.
- Quoting preserves -x as one argument without removing its leading dash.
- The quoted value -x stays one argument with its dash intact; a different utility may still parse it as an option.
show() { printf "<%s>\n" "$1"; }
value="-x"
show "$value"
<-x>
Why this result follows: Quoting preserves -x as one argument without removing its leading dash.
14. Pass an option terminator
Problem: Show a documented separator and a dash-leading operand as separate arguments.
- The literal -- and quoted -x are two separate arguments in the receiving function.
- The receiver sees -- and -x as separate arguments, while real option termination depends on the target utility’s documented behavior.
show() { printf "%s|%s\n" "$1" "$2"; }
value="-x"
show -- "$value"
--|-x
Why this result follows: The literal -- and quoted -x are two separate arguments in the receiving function.
15. Keep a semicolon as data
Problem: Pass a semicolon within one quoted value.
- The semicolon is supplied through a quoted expansion after shell parsing.
- The semicolon enters through quoted expansion after parsing, so it remains part of a;b rather than separating commands.
show() { printf "<%s>\n" "$1"; }
value="a;b"
show "$value"
<a;b>
Why this result follows: The semicolon is supplied through a quoted expansion after shell parsing.
16. Keep a percent sign as data
Problem: Print user-like text with a fixed printf format.
- The fixed format contains the conversion; the percent sign is in the separate data argument.
- A fixed %s format treats the percent in 50% as argument data instead of a formatting directive.
value="50%"
printf "%s\n" "$value"
50%
Why this result follows: The fixed format contains the conversion; the percent sign is in the separate data argument.
17. Count an empty array
Problem: Pass an empty array to a receiving helper.
- Quoted array-at expansion of an empty array produces no arguments.
- The empty array has no elements to expand, so the receiving function obtains zero positional arguments.
args=()
show() { printf "%s\n" "$#"; }
show "${args[@]}"
0
Why this result follows: Quoted array-at expansion of an empty array produces no arguments.
18. Count one empty array element
Problem: Pass one empty array element to a receiving helper.
- The array has one element whose value is empty.
- An array with one assigned empty element expands to one argument, distinguishable from the zero-element case.
args=("")
show() { printf "%s|<%s>\n" "$#" "$1"; }
show "${args[@]}"
1|<>
Why this result follows: The array has one element whose value is empty.
19. Avoid matching an ambient file
Problem: Test a literal wildcard beside a synthetic matching filename.
- The value is quoted even though sample.txt matches the wildcard pattern.
- After creating sample.txt in a private directory, the test quotes *.txt so it remains literal despite a real matching filename.
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cd "$tmp" || exit
touch sample.txt
value="*.txt"
printf "<%s>\n" "$value"
<*.txt>
Why this result follows: The value is quoted even though sample.txt matches the wildcard pattern.
20. Forward after a count check
Problem: Shift one validated option and forward the remaining two values.
- The function verifies three arguments before removing the first with shift.
- The count guard verifies three arguments before shift removes mode; quoted "$@" then forwards the spaced phrase and empty value intact.
receive() { printf "%s|<%s>|<%s>\n" "$#" "$1" "$2"; }
forward() { if (( $# != 3 )); then return 2; fi; shift; receive "$@"; }
forward mode "two words" ""
2|<two words>|<>
Why this result follows: The function verifies three arguments before removing the first with shift.
Common errors and fixes
A phrase becomes two arguments
- Why it happens
- An unquoted expansion was split on shell whitespace.
- How to fix it
- Quote the expansion when passing a single value.
- Prevent it next time
- Test values containing spaces and verify argument count.
A wildcard expands to filenames
- Why it happens
- An unquoted value underwent pathname expansion.
- How to fix it
- Keep the value quoted and use an array for argument lists.
- Prevent it next time
- Test in a directory with a matching filename.
A caller treats a usage error as data
- Why it happens
- The command writes diagnostics to standard output or exits successfully.
- How to fix it
- Write the usage message to standard error and return a nonzero status.
- Prevent it next time
- Assert stdout, stderr, and status independently.
20 practice exercises
1. How many arguments does show_arg "two words" receive?
Show hint
Count arguments after the caller’s source quoting is applied.
Show worked solution
It receives one argument because the quotes preserve the space inside the value. The function prints that one value and returns the status of printf if the output succeeds.
show_arg "two words" receives one argument containing the space. Its exact-count guard succeeds, and quoted "$1" preserves the value when printf receives it.
Check your solution
- The function receives one argument.
- The argument contains two words and their space.
2. What does the array example pass to printf?
Show hint
Quoted array-at expansion provides one argument per element.
Show worked solution
It passes three separate values: a phrase, a literal wildcard, and an empty string. The quoted array expansion preserves all three boundaries instead of splitting or expanding them.
The array passes three values to printf: a phrase, a literal wildcard and an empty string. The quoted expansion preserves each boundary and prevents the wildcard from matching filenames.
Check your solution
- Three separate values are passed.
- The wildcard and empty value remain intact.
3. A helper accepts exactly one argument. What should show "two words" receive?
Show hint
The caller’s quotes preserve the space.
Show worked solution
It receives one argument containing two words. The count guard succeeds, and a quoted "$1" passes the complete phrase to the fixed printf format.
Check your solution
- The function receives one argument
- The argument retains its space
4. A helper accepts exactly one argument, including empty. What should show "" do?
Show hint
An empty quoted string still counts.
Show worked solution
The function receives one empty argument and accepts it under this contract. Its output can display empty markers while its successful status remains independent of the displayed content.
Check your solution
- The argument count is one
- The empty value is accepted
5. A helper requires exactly one argument. What should a call with no arguments return?
Show hint
Check $# before reading $1.
Show worked solution
The guard should return the documented nonzero usage status, such as two, before accessing $1 or performing side effects. Send the usage diagnostic to standard error.
Check your solution
- The missing argument is rejected
- The usage diagnostic and status are separate
6. A helper requires exactly one argument. What should a call with one two do?
Show hint
Two words supplied separately are two arguments.
Show worked solution
The function receives two arguments and rejects the invocation under the exact-one contract. It should not silently ignore the second value or print a success result.
Check your solution
- The count is two
- The invocation returns a usage error
7. A function receives one argument but its numeric value must be between 1 and 10. Is count enough?
Show hint
Count and content are separate rules.
Show worked solution
No. First verify exactly one argument, then validate its numeric grammar and range before use. A single argument can still be empty, nonnumeric or out of range.
Check your solution
- The count is checked first
- Numeric grammar and range are validated separately
8. A value contains two words. Why pass "$value" rather than $value?
Show hint
Unquoted expansion may undergo splitting.
Show worked solution
The quoted expansion supplies the whole value as one argument, retaining its space. An unquoted expansion can split it into multiple arguments and can also trigger filename expansion.
Check your solution
- The quoted value remains one argument
- The embedded space is preserved
9. A value is *.txt and sample.txt exists. What should show "$value" receive?
Show hint
Quoting prevents filename expansion.
Show worked solution
The helper receives the literal string *.txt as one argument even though sample.txt matches the pattern. Test this in a temporary directory and clean up the synthetic file.
Check your solution
- The literal wildcard is received
- The matching fixture does not replace it
10. args=("two words" "*.txt" ""). What does quoted "${args[@]}" pass?
Show hint
Each array element is a separate argument.
Show worked solution
It passes three arguments: the phrase, the literal wildcard and the empty string. The receiving helper can verify a count of three and inspect each value.
Check your solution
- Three arguments are passed
- The final argument is empty
11. A forwarding function receives "red apple" and an empty value. Which expansion should it use?
Show hint
Preserve the positional list.
Show worked solution
Use quoted "$@" when calling the receiver. It forwards the two arguments separately, preserving both the first value’s space and the second value’s emptiness.
Check your solution
- The receiver gets two arguments
- The empty second argument remains
12. An empty array is expanded using "${args[@]}". How many arguments reach a function?
Show hint
An empty array contains no elements.
Show worked solution
Zero arguments reach the function. An array containing one empty string is different and passes one empty argument through the same quoted expansion.
Check your solution
- The receiver gets zero arguments
- An empty array is distinguished from one empty element
13. A helper writes usage to stdout and returns zero on missing input. Why is that misleading?
Show hint
Data, diagnostics and status have different roles.
Show worked solution
A caller can mistake the usage text for successful data and the zero status for success. Write the diagnostic to stderr and return the documented nonzero usage status.
Check your solution
- Usage is written to stderr
- The missing-input status is nonzero
14. A helper validates count after changing a file. What should be changed?
Show hint
Reject invalid input before effects.
Show worked solution
Move the argument-count guard before the file operation and test that an invalid invocation leaves the fixture unchanged. Keep the successful operation’s status and diagnostics explicit.
Check your solution
- The guard precedes the side effect
- A rejected invocation leaves the fixture unchanged
15. A quoted path is -x. Does quoting ensure a utility treats it as an operand?
Show hint
The utility interprets its own arguments.
Show worked solution
No. Quoting keeps -x as one argument but leaves its leading dash intact. Use the utility’s documented -- separator or an appropriate explicit pathname where supported.
Check your solution
- The leading dash remains
- The utility’s option convention is checked
16. A value contains a semicolon and is passed as "$value". Does it start another command?
Show hint
Shell parsing precedes parameter expansion.
Show worked solution
No. The semicolon is part of the quoted argument supplied after parsing. Passing data directly avoids a second parse that could reinterpret it as shell syntax.
Check your solution
- The receiver gets the literal semicolon
- No second command is created by expansion
17. A value is 50%. How should a helper print it?
Show hint
Keep the printf format fixed.
Show worked solution
Use a fixed %s format and pass the quoted value as an argument. The percent sign then remains data rather than becoming part of the format string.
Check your solution
- The format is fixed
- The output contains the literal percent sign
18. A function must shift one required argument before forwarding others. What comes first?
Show hint
Validate the count before shift.
Show worked solution
Check that the required argument exists, then shift and forward the remaining list with quoted "$@". Return a documented usage error if the count is insufficient.
Check your solution
- The count guard precedes shift
- Remaining arguments preserve their boundaries
19. A path argument is quoted and contains ../outside. Does quoting authorize it?
Show hint
Boundary preservation is not path policy.
Show worked solution
No. Quoting passes ../outside as one argument but does not determine whether the destination is permitted. Apply the application’s separate path validation and authorization rules.
Check your solution
- The path remains one argument
- Authorization is checked separately
20. How can a test distinguish successful data from a usage error?
Show hint
Inspect three outcomes independently.
Show worked solution
Assert the exit status, standard output and standard error separately for both a valid and an invalid call. Also verify that the invalid call did not perform the protected side effect.
Check your solution
- Status and both streams are asserted
- Rejected input has no protected side effect
Key takeaways
- Treat an argument list as structured data.
- Quote expansions and test status and output streams.
- An empty argument is different from a missing argument.
- Quoted expansions and arrays preserve intended boundaries.
- Usage errors need a nonzero status and a diagnostic channel.