shell编程 - 函数
1. 函数默认退出状态码
function isDirExist {
local dir=$1
ls $dir
}
dir=/path/test/
isDirExist "$dir"
if [ $? -eq 1 ]
then
echo "The $dir is not exist"
exit
fi
如果函数最后的ls 命令成功执行默认返回0,如果失败默认返回1
默认退出状态码的缺点是最后一句代码决定了函数最终的状态码,如果有多个语句无法判断其他语句是否成功执行.
2. 函数通过return语句返回数字 0 或 1
function isDirExist {
local dir=$1
if [ -d "$dir" ]
then
return 0
else
return 1
fi
}
dir=/path/test/
isDirExist "$dir"
if [ $? -eq 1 ]
then
echo "The $dir is not exist"
exit
fi
通过主动返回数字来确认,函数是否成功执行,用 0代表true,1 代表false,也可以使用其他数字,但这样更加直观
通过return语句返回得到函数的执行结果,缺点是只能返回数字不能返回字符串,并且数字的范围是0~255
3. 函数通过echo语句输出结果
function isDirExist {
local dir=$1
if [ -d "$dir" ]
then
echo "true"
else
echo "false"
fi
}
dir=/path/test/
isExist=$(isDirExist "$dir")
if [ $isExist = "false" ]
then
echo "The $dir is not exist"
exit
fi
通过echo语句可以使函数调用得到更多类型的值
4. 函数局部变量
- 函数内定义的变量默认为全局变量
- 在函数内定义的变量名前面加local 关键字可以使全局变量变为局部变量
- 通过$1, $2, $3 获取函数调用时传递的实参
- 通过$# 获取参数个数
5. 编写函数的建议
- 函数内建议使用局部变量,以避免与无意中修改全局变量
- 建议不要直接使用$1 $2 ,将他们赋值给一个局部变量可以使代码具有更好的可读性
- 建议使用return 或者 echo 得到函数的执行结果,不要使用默认退出状态码