本文摘自PHP中文网,作者不言,侵删。
本篇文章将给大家介绍关于如何在shell脚本中创建和使用函数,下面我们来看具体的内容。
在Shell脚本中创建第一个函数
在shell脚本中创建第一个函数,显示输出“Hello World!”。使用以下代码创建shell脚本“script.sh”。
1 2 3 4 5 6 7 8 9 | #!/bin/bash
funHello(){
echo "Hello World!" ;
}
# Call funHello from any where in script like below
funHello
|
执行脚本:
1 2 3 4 | # sh script.sh
ouput:
Hello World!
|
如何将参数传递给shell脚本中的函数
向函数传递参数与从shell向命令传递参数类似。函数接收$1、$2…等的参数。使用以下代码创建shell脚本。
1 2 3 4 5 6 7 8 9 10 11 12 | #!/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
|
执行脚本:
1 2 3 4 5 6 7 | # sh script.sh
Ouput:
First Argument : First
Second Argument : 2
Third Argument : 3.5
Fourth Argument : Last
|
如何从Shell脚本中的函数接收返回值
有时我们还需要从函数返回值。使用以下示例从shell脚本中的函数获取返回值。
1 2 3 4 5 6 7 | #!/bin/bash
funReturnValues(){
echo "5"
}
# Call funReturnValues from any where in script and get return values
values =$(funReturnValues)
echo "Return value is : $values"
|
执行脚本
如何在shell脚本中创建递归函数
调用自身的函数称为递归函数。下面的示例显示如何使用递归函数打印1到5位数字。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/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
|
执行脚本:
1 2 3 4 5 6 7 8 | # sh script.sh
Ouput:
1
2
3
4
5
|
本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的Linux教程视频栏目!
以上就是如何在Bash Shell脚本中使用函数的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
如何在bash shell脚本中使用函数
如何检查bash中是否存在文件或目录
总结bash中常用特殊字符
linux下关于bash提示符的一些操作详解
linux bash是什么?
总结bash中常用特殊字符
bash shell:测试文件或目录是否存在
bash和dos有什么区别
用于mysql数据库备份的简单bash脚本的介绍
如何在bash shell中使用换行符(\n)
更多相关阅读请进入《bash》频道 >>
转载请注明出处:木庄网络博客 » 如何在Bash Shell脚本中使用函数