Learning Objectives
- Learn the concept and usage of functions in Shell.
- Understand how to define and call sequences of commands in functions.
- Master how to pass parameters to functions and get the return value.
- Practice writing scripts and modularly program using functions.
Learning content
Today we will learn how to define and use functions in shell programming, and how to pass parameters to functions.
1. Function definition and call
In Shell we can usefunction
Keywords or directly use function names to define functions.
# Define functions using the `function` keyword function my_function() { # Command Sequence command1 command2 } # Directly use function names to define functions my_function() { # Command Sequence command1 command2 }
We can call a function through the function name and execute the command sequence defined in the function.
my_function
2. Parameter passing
We can pass parameters to the function and get the value of the parameter in the function. In the function, you can use$1
、$2
Equal variables to refer to the parameters passed to the function.
# Passing parameters to functionsmy_function() { echo "Hello, $1!" } # Call the function and pass the parametersmy_function "daShuGe"
In the above example, we go to the functionmy_function
Pass parametersdaShuGe
and use it in the function$1
to get the value of the parameter and execute the resultHello, “daShuGe”!
。
3. Return value
Functions can be usedreturn
The statement returns a value. The return value of the function can be passed$?
Come to get it.
# Define a function with a return value get_square() { local num=$1 local square=$((num * num)) return $square } # Call the function and get the return value get_square 5 result=$? echo "The square is: $result"
In the above example, the functionget_square
Calculate the square of the incoming parameters and usereturn
The statement returns the result. We passed$?
to get the return value and store it in a variableresult
In, the execution result is“The square is:25”
。
4. Practice tasks
# Define the function and print the passed parameters print_name() { echo "Hello, $1!" } # Call the function and pass the parameters print_name "Alice" # Define the function, calculate the sum of two numbers and return the resultadd_numbers() { local num1=$1 local num2=$2 local sum=$((num1 + num2)) return $sum } # Call the function and get the return valueadd_numbers 10 20 result=$? echo "The sum is: $result"
In the practice task, we define two functions:print_name
Used to print incoming parameters,add_numbers
Used to calculate the sum of two numbers and return the result. We call these two functions and pass the corresponding parameters.
This is the article about the basic concepts and usage of shell function and parameter transfer. For more related shell function parameter transfer, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!