Why does if [ …something… ]; then echo “Exit status is $?” always emit 0?

让人想犯罪 __ 提交于 2021-02-05 09:46:34

问题


What is the correct way to output an exit status in bash? As far as I know, the exit status called by $? corresponds to the status of the last command executed.

The script being worked on has a few conditional checks on the files fed as arguments, for example, a check on whether any files were named at all or if a file exists or not.

So I have conditional statements like this:

if [ $# -eq 0 ] ; then
     echo "No file name(s) given! \nExit status=$?"
     exit

if [ ! -e "$fName" ] ; then
     echo "$fName does not exist! \nExit status=$?"
     exit 

But these return an exit status of 0. I'm not entirely sure even what exit codes would be appropriate for each of these situations, but I think both 1 would work for both based on this. Should I just hard-code the 1 into the conditional statement or change the logic so unix outputs an error code? Also, what command would the 0 that I get for the above example be the exit code for?


回答1:


In both of these cases, the last command executed was [, which exited with 0 status ("success") to land you in the "true" block.

Yes, you need to specify a non-zero exit code for the exit command.

Pedantically "unix" does not output the error code: it's the shell running your script that exits with the specified status.



来源:https://stackoverflow.com/questions/51053475/why-does-if-something-then-echo-exit-status-is-always-emit-0

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