Shell 函数
2019-07-26 本文已影响0人
tafanfly
shell 的函数化一是脚本结构清晰明了, 二是可以重复使用相同代码。
shell 函数必须先定义后才能引用。
函数结构
- 函数构造 : 可以function name()定义,也可以name()定义
- 函数参数:在函数体内部,通过 $n 的形式来获取参数的值
- 函数返回:返回值只能是整数
#!/bin/bash
function name(){
body
return
}
函数举例
参数
在函数内部, 通过 $n
的形式来获取参数的值。$
0表示脚本的名称, $
1表示函数第一个参数, $
2表示函数第二个参数,以此类推。
注意
:$10 不能获取第十个参数,获取第十个参数需要 ${10}。当 n>=10 时,需要使用 ${n} 来获取参数。
#!/bin/bash
function test_parameters(){
echo "The zero value is $0"
echo "The first value is $1"
echo "The second value is $2"
echo "The tenth value is $10"
echo "The tenth value is ${10}"
echo "The sum of values is $#"
echo "The total values are $*"
}
test_parameters 1 2 3 4 5 6 7 8 9 22 33
$ sh test.sh
The zero value is test.sh
The first value is 1
The second value is 2
The tenth value is 10
The tenth value is 22
The sum of values is 11
The total values are 1 2 3 4 5 6 7 8 9 22 33
返回
shell 函数只能return
整型。
- 函数返回值在调用该函数后通过
$?
来获得,注意的是$?
仅对其上一条指令负责
#!/bin/bash
function test_return(){
return 2
}
test_return
echo $? # 返回 test_return的返回值
echo $? # 返回上一条命令的值
$ sh test.sh
2
0
- 如果没有return, 则以最后一条命令运行结果,作为返回值,且值的范围是[0, 255],0表示成功,其他值表示失败。
#!/bin/bash
function test_return(){
echo 'OK'
}
test_return
echo $? #没有return,则返回最后一条命令运行结果
$ sh test.sh
OK
0
#!/bin/bash
function test_return(){
ech 'OK'
}
test_return
echo $?
$ sh test.sh
test.sh: line 4: ech: command not found
127
- 如果 return 其他数据,比如一个字符串,往往会得到错误提示:“numeric argument required”
#!/bin/bash
function test_return(){
return 'OK'
}
test_return
echo $?
$ sh test.sh
test.sh: line 4: return: OK: numeric argument required
2
- 可以先定义一个变量,用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值
#!/bin/bash
function test_return(){
echo "OK"
}
result=`test_return`
echo $result
result2=$(test_return)
echo $result2
$ sh test.sh
OK
OK