shell脚本编程系列
函数是一个脚本代码块,可以为其命名并在脚本中的任何位置重用它。每当需要在脚本中使用该代码块时,直接写函数名即可。称作调用函数。
创建函数
- 方式1:
function name {commands
}
name定义了该函数的唯一名称,脚本中的函数名不能重复。
- 方式二:
name(){commands
}
函数名后的空括号表明正在定义的是一个函数。
使用函数
#!/bin/bash
# using a function in a scriptfunction func1 {echo "This is an example of a function"
}count=1
while [ $count -le 5 ]
dofunc1count=$[ $count + 1 ]
doneecho "This is the end of the loop"
func1
echo "Now this is the end of the script"
函数定义不一定非要放在shell脚本的开始部分,但是试图在定义之前调用它,会报错Command not found。
函数名必须是唯一的,如果定义了同名函数,那么新定义就会覆盖原先的定义。
#!/bin/bash
# testing using a duplicate function namefunction func1 {
echo "This is the first definition of the function name"
}func1function func1 {echo "This is a repeat of the same function name"
}func1
echo "This is the end of the script"
函数返回值
bash shell把函数视为一个小型脚本,运行结束时会返回一个退出状态码。
在默认情况下,函数的退出状态码是函数中最后一个命令返回的退出状态码。函数执行结束后,可以使用表准变量$?
来确定函数的退出状态码。
#!/bin/bash
# testing the exit status of a functionfunc1() {echo "trying to display a non-existent file"ls -l badfile
}echo "testing the function: "
func1
echo "The exit status is: $?"
使用函数的默认退出状态码是一个危险的事情。函数最后一个命令决定了退出状态码,即便前面的命令失败了,函数的退出状态码也可能为0.
#!/bin/bash
# testing the exit status of a functionfunc1() {ls -l badfileecho "This was a test of a bad command"
}echo "testing the function:"
func1
echo "The exit status is: $?"
使用return命令
bash shell会使用return命令以特定的退出状态码退出函数,return命令允许指定一个整数值作为函数的退出状态码,从而提供一种简单的编程设定方式。要注意,退出状态码最大为255的整数,超过了这个值会发生溢出。
#!/bin/bash
# using the return command in a functionfunction dbl {read -p "Enter a value: " valueecho "doubling the value"return $[ $value * 2 ]
}dbl
echo "The new value is $?"
函数的输出可以保存到shell变量当中,比如result=$(dbl)
#!/bin/bash
# using the echo to return a valuefunction dbl {read -p "Enter a value: " valueecho $[ $value * 2 ]
}result=$(dbl)
echo "The new value is $result"
上面函数使用标准的echo语句返回值。除此之外,还可以通过反引号来获取输出的数据。
#!/bin/bash
# using recursionfunction factorial {if [ $1 -eq 1 ]thenecho 1elselocal temp=$[ $1 - 1 ]local result=$(factorial $temp)echo $[ $result * $1 ]fi
}read -p "Enter value: " value
result=$(factorial $value)
echo "The factorial of $value is: $result"
在上面的递归调用时,通过$(factorial $temp)
调用factorial函数,也就是自己。实现了阶乘的算法。