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

时间:2019-05-19 01:26:29  来源:igfitidea点击:

函数是什么:
一个函数也可以称为子程序,过程是用于特定任务的代码块。
函数还有一个属性叫做可重用性。
本教程将如何在shell脚本中创建和使用函数。

在Shell脚本中创建第一个函数

创建第一个函数:在shell脚本显示输出“Hello World!”
创建shell脚本“script.sh”。

# vim script.sh

#!/bin/bash

funHello(){
    echo "Hello World!";
}

# 在脚本中的任何地方调用funHello

funHello

执行脚本

# sh script.sh
ouput:

Hello World!

在Shell脚本中如何向函数传递参数

向函数传递参数就像从shell向命令传递参数一样。
函数接收参数为$1,$2,$3等等。
使用以下代码创建一个shell脚本。

# vim script.sh

#!/bin/bash

funArguments(){
   echo "First Argument : "
   echo "Second Argument : "
   echo "Third Argument : "
   echo "Fourth Argument : "
}

# 调用函数时传递参数

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"
}

# 调用 funReturnValues 并获取返回值

values=$(funReturnValues)
echo "返回值是: $values"

执行脚本

#  sh script.sh

返回值是:5

如何在Shell脚本中创建递归函数

调用自身的函数称为递归函数。
下面的例子显示了用递归函数打印1到5位数字。

# vim script.sh

#!/bin/bash

funRecursive(){
val=
if [ $val -gt 5 ]
then
	exit 0
else
	echo $val
fi
val=$((val+1))
funRecursive $val     # Function calling itself here
}

# 在脚本中任何地方调用 funRecursive

funRecursive 1

执行脚本

# sh script.sh

1
2
3
4
5