为什么在shell中0为真而假为1? [英] Why 0 is true but false is 1 in the shell?
问题描述
false; echo $?
上面会输出1
,这和我知道的所有其他编程语言都是矛盾的.
The above will output 1
, which is contradictory with all other programming languages I know.
这有什么原因吗?
推荐答案
这是一种约定,但仔细想想,它特别有用.一般来说,如果一个程序成功了,这就是你需要知道的一切.但是,如果失败,您可能需要了解有关失败的各种信息——为什么会发生、如何修复等.零均值成功"和非零均值失败让您可以很容易地检查是否成功,并根据需要调查特定错误以获取更多详细信息.许多 API 和框架都有类似的约定 - 成功的函数返回 0,失败的函数返回描述特定失败情况的错误代码.
It's a convention, but a particularly useful one when you think about it. In general, if a program succeeds that's all you need to know. If it fails, however, you might need to know all kinds of information about the failure - why it happened, how to fix it, etc. Having zero mean 'success' and non-zero mean failure lets you can check pretty easily for success, and investigate the particular error for more details if you want to. A lot of APIs and frameworks have a similar convention - functions that succeed return 0 and and those that fail give back an error code describing the particular failure case.
这篇关于为什么在shell中0为真而假为1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!