在Bash Shell脚本中使用函数的方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

在Shell脚本中创建第一个函数
在shell脚本中创建第一个函数,显示输出“Hello World!”。使用以下代码创建shell脚本“script.sh”。
# vim script.sh
#!/bin/bash
funHello(){
    echo "Hello World!";
}
# Call funHello from any where in script like below
funHello执行脚本:
# sh script.sh ouput: Hello World!
如何将参数传递给shell脚本中的函数
向函数传递参数与从shell向命令传递参数类似。函数接收$1、$2…等的参数。使用以下代码创建shell脚本。
# vim script.sh
#!/bin/bash
funArguments(){
   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 below
funArguments First 2 3.5 Last执行脚本:
# sh script.sh Ouput: First Argument : First Second Argument : 2 Third Argument : 3.5 Fourth Argument : Last
如何从Shell脚本中的函数接收返回值
有时我们还需要从函数返回值。使用以下示例从shell脚本中的函数获取返回值。
# vim script.sh
#!/bin/bash
funReturnValues(){
echo "5"
}
# Call funReturnValues from any where in script and get return values
values=$(funReturnValues)
echo "Return value is : $values"执行脚本
# sh script.sh Ouput: 5
如何在shell脚本中创建递归函数
调用自身的函数称为递归函数。下面的示例显示如何使用递归函数打印1到5位数字。
# vim script.sh
#!/bin/bash
funRecursive(){
val=$1
if [ $val -gt 5 ]
then
exit 0
else
echo $val
fi
val=$((val+1))
funRecursive $val     # Function calling itself here
}
# Call funRecursive from any where in script
funRecursive 1执行脚本:
# sh script.sh Ouput: 1 2 3 4 5
感谢各位的阅读!看完上述内容,你们对在Bash Shell脚本中使用函数的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注创新互联成都网站设计公司行业资讯频道。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
当前文章:在BashShell脚本中使用函数的方法-创新互联
本文网址:http://www.cqwzjz.cn/article/doohcj.html

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询 
 