Shell script function
One, Shell function
- Write the sequence of commands together in a format
- Easy to reuse command sequence
1.Shell function definition
方法一:
function 函数名 {
命令序列
}
方法二:
函数名() {
命令序列
}
2. The return value of the function
return means to exit the function and return an exit value, which can be displayed by the $? variable in the script
Usage principles:
1. Take the return value as soon as the function ends, because the $? variable only returns the exit status code of the last command executed.
2. The exit status code must be 0~255, and the value will be divided by 256 if it exceeds
return
echo
Two, function parameter transfer
#!/bin/bash
sum() {
s=$[$1 + $2]
echo $s
}
read -p "请输入第一个参数:" first
read -p "请输入第二个参数:" second
sum $first $second
Three, the scope of function variables
- Functions in Shell scripts are only valid in the current Shell environment
- Variables in Shell scripts are globally effective by default
- Use the local command to limit the variable to the function
Four, recursion
1. Factorial
fact() {
if [ $1 -eq 1 ]
then
echo 1
else
local temp=$[$1 - 1]
local result=$(fact $temp)
echo $[$1 * $result]
fi
}
read -p "请输入:" n
result=$(fact $n)
echo $result
2. Recursive directory
#!/bin/bash
listdir () {
for i in $1/*
do
if [ -d $i ]
then
echo "$2$i:"
listdir $i " $2"
else
echo "$2$i"
fi
done
}
read -p "请输出目录名:" dir
listdir $dir ""
Five, create a library