创建函数
function name {
commands
}
$ cat test2
#!/bin/bash
# using a function located in the middle of a script
count=1
echo "This line comes before the function definition"
function func1 {
echo "This is an example of a function"
}
while [ $count -le 5 ]
do
func1
count=$[ $count + 1 ]
done
echo "This is the end of the loop"
func2
echo "Now this is the end of the script"
function func2 {
echo "This is an example of a function"
}
$
$ ./test2
This line comes before the function definition
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is an example of a function
This is the end of the loop
./test2: func2: command not found
Now this is the end of the script
$
函数输出
$ cat test5b
#!/bin/bash
# using the echo to return a value
function dbl {
read -p "Enter a value: " value
echo $[ $value * 2 ]
}
result=$(dbl)
echo "The new value is $result"
$
$ ./test5b
Enter a value: 200
The new value is 400
$
$ ./test5b
Enter a value: 1000
The new value is 2000
$
向函数传递参数
#!/bin/bash
function add {
if [ $# -eq 0 ] || [ $# -gt 2 ]
then
echo -1
elif [ $# -eq 1 ]
then
echo $[ $1 + $1 ]
else
echo $[ $1 + $2 ]
fi
}
echo -n "10+15="
value=$(add 10 15)
echo $value
echo -n "just one number:"
value=$(add 10)
echo $value
echo -n "no number:"
value=$(add)
echo $value
echo -n "three number:"
value=$(add 10 15 20)
echo $value
输出
./test14
10+15=25
just one number:20
no number:-1
three number:-1
要在函数中使用脚本的命令行参数,必须在调用函数时手动将其传入
cat test15
#!/bin/bash
function func2 {
echo $[ $1 + $2 ]
}
if [ $# -eq 2 ]
then
value=$( func2 12 13)
echo "$1+$2=$value"
else
echo "Please input two value"
fi
输出:
./test15 12 13
12+13=25
./test15
Please input two value
变量
全局变量
在默认情况下,在脚本中定义的任何变量都是全局变量
局部变量
无须在函数中使用全局变量,任何在函数内部使用的变量都可以被声明为局部变量。为此,只需在变量声明之前加上local关键字即可:
#!/bin/bash
function func1 {
local temp=$[ $value + 5 ]
result=$[ $temp * 2 ]
value=$[ $value * 2 ]
}
temp=4
value=6
echo "temp=$temp"
echo "value=$value"
func1
echo "local局部变量temp:"$temp #局部变量
echo "全局变量value:"$value #全局变量
输出:
./test16
temp=4
value=6
local局部变量temp:4
全局变量value:12
递归-阶乘函数
cat test17
#!/bin/bash
#递归
function factorial {
if [ $1 -eq 1 ]
then
echo 1
else
local temp=$[ $1 - 1 ]
local result=$(factorial $temp)
echo $[ $result * $1 ]
fi
}
read -p "请输入值:" value
result=$(factorial $value)
echo "数据$value的阶乘是:$result"
输出:
./test17
请输入值:3
数据3的阶乘是:6