Bash Shell脚本函数示例
时间:2020-01-09 10:37:26 来源:igfitidea点击:
如何在UNIX/Linux操作系统下使用Bash创建Shell脚本函数?
函数不过是Bash shell脚本中的小子例程或下标。
您需要用于将复杂的脚本分解为单独的任务。
这样可以提高脚本的整体可读性和易用性。
但是,shell函数无法返回值。
他们返回状态码。
声明shell函数
必须先声明所有函数,然后才能使用它们。
语法为:
function name(){
Commands
}
或者
name(){
Commands
return $TRUE
}
您可以通过输入函数名称来调用函数:
name
例子
创建一个名为file.sh的shell脚本:
#!/bin/bash
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
usage(){
echo "Usage: chmod +x file.sh
./file.sh
./file.sh /etc/resolv.conf
filename"
exit 1
}
# define is_file_exits function
# $f -> store argument passed to the script
is_file_exits(){
local f=""
[[ -f "$f" ]] && return 0 || return 1
}
# invoke usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage
# Invoke is_file_exits
if ( is_file_exits "" )
then
echo "File found"
else
echo "File not found"
fi
如下运行:
fname(){
echo "Foo"
}
export -f fname
导出函数
您需要使用导出命令:
fname(){
echo "Foo"
}
usage(){
echo "Usage: #!/bin/bash
# gloabal x and y
x=200
y=100
math(){
# local variable x and y with passed args
local x=
local y=
echo $(( $x + $y ))
}
echo "x: $x and y: $y"
# call function
echo "Calling math() with x: $x and y: $y"
math 5 10
# x and y are not modified by math()
echo "x: $x and y: $y after calling math()"
echo $(( $x + $y ))
foo bar"
exit 1
}
readonly -f usage
readonly -f fname
设置只读函数
您可以在脚本顶部创建函数,并使用readonly命令设置readonly属性:
#!/bin/bash
foo(){
# do something
# if not false call foo
foo
}
# call foo
foo
局部变量函数
使用local命令创建局部变量:
##代码##递归
递归函数调用本身。
递归是一种有用的技术,用于简化某些复杂的算法并解决复杂的问题。
有关更多详细信息,请参见递归函数。

