Shell 函数

2019-07-26  本文已影响0人  tafanfly

shell 的函数化一是脚本结构清晰明了, 二是可以重复使用相同代码。
shell 函数必须先定义后才能引用。

函数结构

#!/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
#!/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
#!/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
上一篇 下一篇

猜你喜欢

热点阅读