Function return values within BASH if statements

若如初见. 提交于 2021-01-08 09:00:54

问题


I have looked at various ways on here handle function return values within BASH if-then statements, but none seem to work. Here is what I've got

 function is_cloned()
 {
      if [ -d $DIR_NAME ]
      then
           return $SUCCESS
      fi
      return $FAILURE
 }

It will work if I call it on its own and check the return value like:

 is_cloned
 retval=$?
 if [ $retval -eq $FAILURE ] 
 then
      ...
 fi

How can I use the function call within the if statement? Or is there no way at all to take advantage of the return values?


回答1:


if statements in Bash can use the exit code of functions directly. So you can write like this:

if is_cloned
then
    echo success
fi

If you want to check for failure, as in your posted code, you could use the ! operator:

if ! is_cloned
then
    echo failure
fi

By the way, your is_cloned function too can rely more on exit codes, you can write like this:

is_cloned() {
    [ -d "$DIR_NAME" ]
}

This works, because the exit code of a function is the exit code of the last executed command, and the exit code of [ ... ] is 0 if successful, non-zero otherwise (= failure).

Also remember to double-quote variable names used as command arguments, as I did DIR_NAME here.



来源:https://stackoverflow.com/questions/46694112/function-return-values-within-bash-if-statements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!