Pre-knowledge requirements
- Linux command line basics
- Basic concepts of Shell programming
How do I create a function
A:
#! /usr/bin/env bash
function myFunc {
commands
}
Copy the code
Method 2:
#! /usr/bin/env bash
myFunc () {
commands
}
Copy the code
MyFunc is the name of the function, and every function defined in the script must have a unique name. If there are more than one function with the same name, the later definition will override the previous one, and more importantly, it will not cause any errors!!
How do I call a function
#! /usr/bin/env bash
function myFunc {
echo "This is our first function demo."
}
Use the function name directly, just like any other shell command
myFunc
Copy the code
The function must be defined before it can be used, otherwise “Command not found” will be displayed.
How do I define local variables in functions
By default, variables defined in a script are all variables. Variables defined outside a function can be used freely inside the function. Similarly, global variables defined inside a function can be read and written elsewhere in the script.
This is too messy and unsafe, so we need a way to define local variables inside functions. This is the local command provided by the bash shell.
#! /usr/bin/env bash
top="top"
function testLocalVar {
# global variable
ridge="ridge"
# local variable
local regional="regional"
echo "function interior, access global variable 'top': $top"
echo "function interior, access local variable 'regional': $regional"
}
testLocalVar
echo
echo "script top, access global variable 'ridge' defined in function: $ridge"
echo "script top, access function interior local variable 'regional': $regional"
Copy the code
How do I pass parameters to a function
Bash shells treat functions as small scripts. So we can pass arguments to a function like a normal script. That is, functions can use standard environment variable arguments to represent arguments passed to functions:
$0
: function nameThe $1
: the first argument to the function$2
: the second argument to the function$#
: The number of arguments to the function$*
: All arguments to a function are saved as a single word (treat the arguments as a whole rather than as individual individuals)$@
: All arguments to a function are treated as independent words in the same string
#! /usr/bin/env bash
function printName {
echo "Hello The $1"
}
user="juejin"
The argument must be on the same line as the function name:
printName $user
Copy the code
How do I pass parameter values from the script command line to a function
#! /usr/bin/env bash
function printCommandLineParams {
echo "the first parm from command line input is: The $1"
}
Pass special environment variable parameters from the script to the function manually
printName The $1
Copy the code
How do you pass an array to a function
Unfortunately, you can’t pass an array variable to a function as a single argument in Bash; The only way to do this is to expand the array and create a new one inside the function.
#! /usr/bin/env bash
function printArray {
newArr=("$@")
echo "${newArr[*]}"
}
aArr=(1 2 3 4 5)
printArray "${aArr[*]}"
Copy the code
How do I return a value from a function
The exit status code of the function
The Bash shell treats the function like a small script that returns a status code at the end of the run. By default, the exit status code of a function is the exit status code returned by the last command in the function. At the end of the function, you can use the standard variable $? To determine the exit status code of the function.
#! /usr/bin/env bash
function testStatusCode {
ls -l non-existent
echo "trying to display a non-existent file"
}
testStatusCode
echo "The exit code status is: $?"
Copy the code
In the above code, the last command in the function executed successfully, so the exit status code of the function is 0, even if there is an error command inside the function.
The return command
The bash shell uses the return command to exit a function and return a specific exit status code. The return command allows you to specify an integer value to define the exit status code of a function.
#! /usr/bin/env bash
function customStatusCode {
return $(( value * 2 ))
}
value=3
x=$(customStatusCode $value)
echo "The new value is $?"
echo "The x is $x"
Copy the code
The status code for the return command can only be defined by the $? Parameter, and there is no way to output a value. And there are two problems with getting values this way:
- Must be retrieved as soon as the function ends
$?
The value of the return
The value of the command must be 0 to 255
If you are using $? The value of the return command is lost if another command is executed before the value of the variable value. If the return value is not between [0, 255], an error value is generated.
Echo output
Echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo
#! /usr/bin/env bash
function add {
echo $(( The $1 + $2 ))
}
first=1
second=2
sum=$(add $first $second)
echo "the sum of $first and $second is: $sum"
Copy the code
This approach is also problematic if there are multiple echoes inside the function:
#! /usr/bin/env bash
function add {
echo "Hi~I'm add function"
echo $(( The $1 + $2 ))
}
first=1
second=2
sum=$(add $first $second)
echo "the sum of $first and $second is: $sum"
Copy the code
Echo output array
Just as you pass array parameters to a function, you can’t output an array variable as a single variable value in a Shell script. All you can do is print each value in the array in the correct order inside the function, and then reassemble the values into an array outside the function.
#! /usr/bin/env bash
function outputArr {
local originalArr=("$@")
local newArr=("$@")
local len=$#
local i=0
while [ "$i" -lt "$len" ]
do
newArr[$i] = $((${originalArr[$i]} * 2 ))
i=$(( i + 1 ))
done
echo "${newArr[*]}"
}
myArr=(1 2 3)
result=($(outputArr ${myArr[*]}))
echo "The new Arr is : ${result[*]}"
Copy the code
How do you implement recursion
Here is a Bash Script implementation of the factorial function:
#! /usr/bin/env bash
function factorial {
if [ The $1 -eq 1 ]
then
echo 1
else
local temp=$(( The $1 - 1 ))
local result=$(factorial $temp)
echo $(( The $1 * $result ))
fi
}
Copy the code
How do I use a function in another script
Using the source command, we can execute commands in the current Shell context instead of creating a new Shell.
#! /usr/bin/env bash
Assume that the utils.sh file is in the same directory as the current script
source ./utils.sh
With the above command line, we can then use the functions defined in utils.sh
Copy the code
source
Alias of the command
The source command has a quick alias called the dot operator. The previous example can be rewritten as:
#! /usr/bin/env bash
Assume that the utils.sh file is in the same directory as the current script
. ./utils.sh
With the above command line, we can then use the functions defined in utils.sh
Copy the code
reference
- Richard Blum & Christine Bresnahan. Linux Command Line and Shell Scripting (3rd edition). Beijing: Posts and Telecommunications Press.2016