In Shell scripts, passing parameters to functions is similar to passing parameters to scripts. You can call the function by specifying parameters after the function name separated by spaces, and within the function, receive these parameters using positional parameters such as $1, $2, $3, etc.
The following is a simple example demonstrating how to pass parameters to a Shell function and handle them internally:
bash#!/bin/bash # Define a function named greet greet() { # $1 and $2 are the first and second parameters passed to the function echo "Hello, $1! Today is $2." } # Call the function and pass two parameters greet "Alice" "Monday"
In this example, the function greet accepts two parameters. When calling greet "Alice" "Monday", Alice is assigned to $1 and Monday to $2. Thus, the output will be:
shellHello, Alice! Today is Monday.
You can pass any number of parameters as needed, and within the function, access them using $n, where n represents the position of the parameter.
Additionally, if the number of parameters is uncertain, you can use the special variables $@ or $* to receive all parameters. These are generally interchangeable. The key difference is that when enclosed in double quotes, $* treats all parameters as a single string, whereas $@ treats each parameter separately. This is particularly useful when handling parameter lists.
For example:
bash#!/bin/bash # Define a function to print all passed parameters print_all() { for arg in "$@"; do echo $arg done } # Call the function with multiple parameters print_all "Hello" "world" "this" "is" "a" "test"
This script will print each parameter passed to the function print_all individually.