脚本函数基础
创建函数
在 bash shell 脚本中创建函数的语法有两种。第一种语法是使用关键字 function,随后跟上分配给该代码块的函数名:
function name { commands }
name 定义了该函数的唯一名称。脚本中的函数名不能重复。
commands 是组成函数的一个或多个 bash shell 命令。调用该函数时,bash shell 会依次执行函数内的命令,就像在普通脚本中一样。
第二种在 bash shell 脚本中创建函数的语法更接近其他编程语言中定义函数的方式:
name() { commands }
函数名后的空括号表明正在定义的是一个函数。这种语法的命名规则和第一种语法一样。
使用函数
#!/bin/bash # using a function in a script function func1 { echo "This is an example of a function" } count=1 while [ $count -le 5 ] do func1 count=$[ $count + 1 ] done echo "This is the end of the loop" func1 echo "Now this is the end of the script"
函数定义不一定非要放在 shell 脚本的最开始部分,但是要注意这种情况。如果试图在函数被定义之前调用它,则会收到一条错误消息。
函数返回值
bash shell 把函数视为一个小型脚本,运行结束时会返回一个退出状态码,有 3 种方法能为函数生成退出状态码。
默认的退出状态码
在默认情况下,函数的退出状态码是函数中最后一个命令返回的退出状态码。函数执行结束后,可以使用标准变量$?来确定函数的退出状态码:
#!/bin/bash # testing the exit status of a function func1() { echo "trying to display a non-existent file" ls -l badfile } func2() { ls -l badfile echo "trying to display a non-existent file" } echo "testing the function: " func1 echo "The exit status is: $?" func2 echo "The exit status is: $?"
该函数的退出状态码是函数内部最后一条命令执行返回做的状态,上例中func1返回的状态是1(badfile不存在),func2返回的状态是0(最后一条命令执行成功)
使用return命令
bash shell 会使用 return 命令以特定的退出状态码退出函数。return 命令允许指定一个整数值作为函数的退出状态码,从而提供了一种简单的编程设定方式:
#!/bin/bash # using the return command in a function function dbl { read -p "Enter