🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Function Arguments

Function arguments are values passed to a function in its call. Inside the function, $1 holds the first value and $2 holds the second.

Pass two arguments

The call passes the words Ada and Bo to the function. Inside the function, $1 is Ada and $2 is Bo.

show_pair() {
  echo "First: $1"
  echo "Second: $2"
}
show_pair Ada Bo

Count the arguments

The function prints the value of $#. The call passes three words, so the count is three.

count_words() {
  echo "The call gave $# arguments"
}
count_words red green blue

Function arguments differ from script arguments

Run this script with the argument Maya, like bash main.sh Maya. Inside the function $1 is Sam, but outside the function $1 is still Maya.

show_name() {
  echo "Inside the function: $1"
}
show_name Sam
echo "Outside the function: $1"

Example

greet_person() {
  echo "Hello, $1 $2"
  echo "That call gave $# arguments"
}
greet_person Maya Chen
greet_person Sam Lee

Key points

  • Words after the function name in a call become its arguments.
  • Inside a function, $1 is the first argument of that call.
  • Inside a function, $2 is the second argument of that call.
  • The special variable $# counts the arguments of the current call.
  • Function arguments are separate from the arguments of the whole script.
  • Each new call can pass different values to the same function.

In this example, the same function is called with two different name pairs. Each call sets $1 and $2 to the new words. The count $# is two for both calls.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Inside a function, what does $# hold?