1 函数
1.1 定义
function NAME(){
command1
command2
...
}
省略关键字function
NAME(){
command1
...
}
例子:
#!/bin/bash
function sayHello(){
echo "Hello"
}
sayHello #函数调用
1.2 函数的返回值
函数的返回值又叫函数的退出状态。
例子:
#!/bin/bash
FILE=/etc/notExistFile
function checkFileExist(){
if [ -f $FILE ]; then
return 0
else
return 1
fi
}
echo "Call function checkFileExist" #提示函数调用
checkFileExist
RTV=$? #将函数返回值保存在变量中
if [ $RTV -eq 0]; then
echo "$FILE exist"
else
echo "FILE not exist"
fi
2 带参数的函数
2.1 位置参数
#!/bin/bash
function checkFileExist(){
if [ -f $1]; then
return 0
else
return 1
fi
}
echo "Call function checkFileExist" #提示函数调用
checkFileExist
RTV=$? #将函数返回值保存在变量中
if [ $RTV -eq 0]; then
echo "$1 exist"
else
echo "$1 not exist"
fi
2.2 指定位置参数
set命令给指定脚本指定位置参数(又叫重置)
例子:一个 set01.sh 脚本
#!/bin/bash
set 1 2 3 4 5 6
for i in $@
do
echo "Here \$$COUNT is $i"
let "COUNT++"
done
运行 bash set01.sh a b c d e f