SoFunction
Updated on 2025-03-10

Shell function parameters

In a shell, a function can be called and the parameters can be passed to it. Inside the function body, the value of the parameter is obtained in the form of $n. For example, $1 represents the first parameter and $2 represents the second parameter...

Example of function with parameters:

#!/bin/bash
funWithParam(){
  echo "The value of the first parameter is $1 !"
  echo "The value of the second parameter is $2 !"
  echo "The value of the tenth parameter is $10 !"
  echo "The value of the tenth parameter is ${10} !"
  echo "The value of the eleventh parameter is ${11} !"
  echo "The amount of the parameters is $# !"
  echo "The string of the parameters is $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

Output:

The value of the first parameter is 1 !
The value of the second parameter is 2 !
The value of the tenth parameter is 10 !
The value of the tenth parameter is 34 !
The value of the eleventh parameter is 73 !
The amount of the parameters is 12 !
The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"

Note that $10 cannot get the tenth parameter, ${10} is required to get the tenth parameter. When n>=10, ${n} needs to be used to get the parameters.

In addition, there are several special characters used to handle parameters:

Parameter processing illustrate
$# Number of parameters passed to the script
$* Display all parameters passed to the script as a single string
$$ The current process ID number of the script running
$! ID number of the last process running in the background
$@ Same as $#, but when used, with quotes and returns each parameter in quotes.
$- Displays the current options used by the shell, the same function as the set command.
$? Displays the exit status of the last command. 0 means no error, and any other value indicates an error.