您好,欢迎访问一九零五行业门户网

如何在Bash Shell脚本中使用函数

本篇文章将给大家介绍关于如何在shell脚本中创建和使用函数,下面我们来看具体的内容。
在shell脚本中创建第一个函数
在shell脚本中创建第一个函数,显示输出“hello world!”。使用以下代码创建shell脚本“script.sh”。
# vim script.sh
#!/bin/bashfunhello(){ echo "hello world!";}# call funhello from any where in script like belowfunhello
执行脚本:
# sh script.shouput:hello world!
如何将参数传递给shell脚本中的函数
向函数传递参数与从shell向命令传递参数类似。函数接收$1、$2…等的参数。使用以下代码创建shell脚本。
# vim script.sh
#!/bin/bashfunarguments(){ echo "first argument : $1" echo "second argument : $2" echo "third argument : $3" echo "fourth argument : $4"}# call funarguments from any where in script using parameters like belowfunarguments first 2 3.5 last
执行脚本:
# sh script.shouput:first argument : firstsecond argument : 2third argument : 3.5fourth argument : last
如何从shell脚本中的函数接收返回值
有时我们还需要从函数返回值。使用以下示例从shell脚本中的函数获取返回值。
# vim script.sh
#!/bin/bashfunreturnvalues(){echo "5"}# call funreturnvalues from any where in script and get return valuesvalues=$(funreturnvalues)echo "return value is : $values"
执行脚本
# sh script.shouput:5
如何在shell脚本中创建递归函数
调用自身的函数称为递归函数。下面的示例显示如何使用递归函数打印1到5位数字。
# vim script.sh
#!/bin/bashfunrecursive(){val=$1if [ $val -gt 5 ]thenexit 0elseecho $valfival=$((val+1))funrecursive $val # function calling itself here}# call funrecursive from any where in scriptfunrecursive 1
执行脚本:
# sh script.shouput:12345
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注的linux教程视频栏目!
以上就是如何在bash shell脚本中使用函数的详细内容。
其它类似信息

推荐信息