函数的作用就是将一段代码包起来,在调用时输入函数名即可,避免重复的相同代码。
一. 函数定义及使用
函数定义的格式:以下三种都可以
函数名() {
命令
}
function 函数名() {
命令
}
function 函数名 {
命令
}
函数调用时,写函数名就可以了。一定要注意的是,调用函数必须在定义之后,否则会报错。
#!/bin/bash
function addition() {
result=$(($1+$2))
}
addition $1 $2
echo $1+$2=$result
function deduction() {
echo $(($1-$2))
}
result=$(deduction $3 $4)
echo $3-$4=$result
这个脚本中,展示了两种在函数中使用变量的方式,需要在外层脚本将变量准备好,函数才能使用。执行结果:
# sh func.sh 12 13 50 33
12+13=25
50-33=17
二. 全局变量和局部变量
1. 全局变量:在函数内外都可定义,都可使用。
#!/bin/bash
function addition() {
result=$(($value1+$value2))
}
value1=$1
value2=$2
result=1
addition $value1 $value2
echo $result
运行结果:
# sh func.sh 12 13
25
虽然 result 在 函数外赋值为 1,但在函数中被修改了。
2. 局部变量:在函数内部定义,函数外部无法使用,格式是变量名前加上 local
#!/bin/bash
function addition() {
local result=$(($value1+$value2))
}
value1=$1
value2=$2
result=1
addition $value1 $value2
echo $result
运行结果:
# sh func.sh 12 13
1
因为 result 是局部变量,在函数以外无法使用,所以输出了 1。
三. 函数返回值
1. 状态码
默认以函数中最后一行代码的退出状态作为函数的退出状态,这是有隐患的,看例子:
#!/bin/bash
function return_test() {
echo "测试返回值"
ls nonefile
}
return_test
echo "$?"
# sh return.sh
测试返回值
ls: cannot access nonefile: No such file or directory
2
这个例子中,因为最后一行正好是报错的,所以函数的退出状态也是非 0 的,可以体现出问题。
#!/bin/bash
function return_test() {
ls nonefile
echo "测试返回值"
}
return_test
echo "$?"
# sh return.sh
ls: cannot access nonefile: No such file or directory
测试返回值
0
当有错误的代码不在最后一行时,函数的状态码也是 0。
2. return 命令
返回当前行代码的退出状态码:
#!/bin/bash
function return_test() {
echo "测试返回值"
return $(ls nonefile)
}
return_test
echo "$?"
# sh return.sh
测试返回值
ls: cannot access nonefile: No such file or directory
2
#!/bin/bash
function return_test() {
return $(ls nonefile)
echo "测试返回值"
}
return_test
echo "$?"
# sh return.sh
ls: cannot access nonefile: No such file or directory
2
四. 函数使用数组
展示一个数组使用的例子:
#!/bin/bash
function array() {
local sum=0
local array_temp=($(echo "$@"))
local new_array=($(echo "$@"))
for (( i=0; i<${#new_array[@]}; i++ ))
do
new_array[$i]=$((${array_temp[$i]} * 2))
done
echo ${array_temp[*]}
echo ${new_array[*]}
}
arrayA=(1 2 3 4 5)
array ${arrayA[*]}
# sh func_array.sh
1 2 3 4 5
2 4 6 8 10
在函数外部定义的普通数组和关联数组都是全局变量,在函数内部定义的普通数组是全局变量,在函数内部定义的关联数组是局部变量:
#!/bin/bash
simpleArray=(a b c)
declare -A relatedArray
relatedArray[a]=1
relatedArray[b]=2
function example() {
simpleArray=(x y z)
declare -A relatedArray
relatedArray[a]=8
relatedArray[b]=9
echo ${simpleArray[@]}
echo ${relatedArray[@]}
}
example
echo ${simpleArray[@]}
echo ${relatedArray[@]}
# sh array.sh
x y z
8 9
x y z
1 2
普通数组 simpleArray 因为都是全局变量,所以在函数内修改了它的值。然而关联数组 relatedArray 在函数外与函数内其实是同名不同值的变量。