BASH / CHAPTER 05

Arrays, functions, and exact argument lists

Intermediate

Pass a collection of shell arguments without flattening it.

By the end of this chapter

  • Expand array elements as separate preserved arguments
  • Forward positional parameters correctly
  • Separate function output from its status

The idea

An indexed Bash array stores a sequence of separate values, including values containing spaces. Quoted "${items[@]}" expands each element into its own argument, while joining the array into one string loses that structure. Positional arguments follow the same rule: quoted "$@" forwards the original argument boundaries, including empty arguments. A command should receive data as arguments rather than through eval.

Functions have positional parameters and can use local variables to avoid changing unrelated caller state. They communicate data through standard output and use return for a numeric status, not for an arbitrary string result. A caller can capture output with command substitution, remembering that trailing newlines are removed. Keep diagnostics on standard error so captured data does not include explanatory messages.

Bash example
#!/usr/bin/env bash
show() {
  local item
  for item in "$@"; do printf '<%s>\n' "$item"; done
}
items=("alpha beta" "" "gamma")
show "${items[@]}"
Result
<alpha beta>
<>
<gamma>

The array expansion preserves three arguments, including the empty middle value. The function forwards that exact structure through its positional parameters.

Try it yourself

Write a function that prefixes each supplied argument and preserves empty arguments.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which expression forwards all original function arguments without flattening them?