为什么[[something ...];然后回显“退出状态为$?".总是发出0? [英] Why does if [ ...something... ]; then echo "Exit status is $?" always emit 0?

查看:63
本文介绍了为什么[[something ...];然后回显“退出状态为$?".总是发出0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中输出退出状态的正确方法是什么?据我所知,由 $?调用的退出状态对应于最后执行的命令的状态.

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 

但是这些返回的退出状态为0.我也不完全确定哪种退出代码适用于每种情况,但是我认为这两个都可以根据

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?

推荐答案

在这两种情况下,最后执行的命令是 [,它以0状态(成功")退出以着陆在"true"块中.

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

是的,您需要为 exit 命令指定一个非零的退出代码.

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

通常,"unix"不会输出错误代码:运行您的脚本的外壳会以指定的状态退出.

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

这篇关于为什么[[something ...];然后回显“退出状态为$?".总是发出0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆