Web Analytics

Function Parameters

Intermediate~25 min read

Use positional parameters to pass values into functions. Prefer $@ for iterating arguments safely, and use shift to consume them.

Positional Parameters

Inside a function, $1 is the first argument, $2 the second, and so on. $# holds the argument count.

Output
Click Run to execute your code
$@ vs $*: Within quotes, "$@" preserves argument boundaries (preferred), while "$*" joins them into a single string.
Pro Tip: When forwarding args to another function, use "$@" to preserve spacing and quoting.
Caution: Unquoted $@ or $* will split on IFS and can break on spaces. Quote your expansions unless you specifically need word splitting.

Common Mistakes

1) Using $* when you need "$@"

# Wrong
show() { for a in "$*"; do echo "[$a]"; done }
show "alpha beta" gamma  # Loses original boundaries

# Correct
show() { for a in "$@"; do echo "[$a]"; done }
show "alpha beta" gamma

2) Forgetting to quote when forwarding

# Wrong
caller() { callee $@; }
callee() { printf '%s\n' "$@"; }
caller "one two" three  # Broken

# Correct
caller() { callee "$@"; }
caller "one two" three

Exercise: Sum Arguments

Task: Implement sum_args that prints the sum of all numeric arguments.

  • Handle any number of args (including 0).
  • Treat non-numeric args as an error and return non-zero.
Output
Click Run to execute your code
Show Solution
sum_args() {
  local n sum=0
  for n in "$@"; do
    [[ $n =~ ^-?[0-9]+$ ]] || return 1
    sum=$((sum + n))
  done
  echo "$sum"
}

sum_args 1 2 3

Summary

  • Use $1..$9 and $# to access and count parameters.
  • Prefer "$@" for iteration to preserve spaces.
  • Use shift to consume parameters in a loop.

What's Next?

Next, learn about return codes and returning computed values in Return Values.