什么是功能:
函数也可以称为子例程,过程是用于特定任务的代码块。函数还有一个属性,称为可重用性。
本教程将帮助您了解如何在 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