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语句可以使函数调用得到更多类型的值