[英]echo $? behaves differently
I have this C program: 我有这个C程序:
int main() { return 10; }
After running this when I write echo $?
运行完这个后我写
echo $?
in the terminal its prints 10
. 在终端上的版画
10
。
Now suppose I have a .sh
file: 现在假设我有一个
.sh
文件:
echo $?
After running the C program if I run the .sh
file it prints 0
. 运行C程序后,如果运行
.sh
文件,它将显示0
。
Why? 为什么?
Simple: the .sh
file gets executed by bash, or some other shell. 简单:
.sh
文件可以通过bash或其他Shell执行。 That binary ( /bin/bash
or wherever it is) executes the script and then exits. 该二进制文件(
/bin/bash
或任何位置)执行脚本,然后退出。 If the shell binary exits successfuly, it returns 0 to the system 如果shell二进制文件成功退出,它将向系统返回0
after your bin returned 10 to the system, and you execute your .sh file, a new shell process starts up (and this shell did not execute your program). 当bin将10返回到系统并执行.sh文件后,新的Shell进程将启动(并且该Shell未执行您的程序)。 So
echo $?
所以
echo $?
probably echoes the return value of another process that the executing shell instance ran (login, or whatever...) 可能会回显正在执行的shell实例运行的另一个进程的返回值(登录,或其他...)
the command echo $?
命令
echo $?
echoes the value that the exit code the last program you executed returned. 回显您执行的最后一个程序的退出代码返回的值。 In case of your C program, it returns 10, so you see 10 show up.
对于您的C程序,它返回10,因此您将看到10。 Your
.sh
file, though is executed by another binary, that returns 0 (upon success), hence echo $?
您的
.sh
文件虽然由另一个二进制文件执行,但返回0(成功后),因此echo $?
shows 0. 显示0。
Suppose you do this: 假设您这样做:
./your_bin
./your.sh
echo $?
//--> echoes 0
./your_bin
echo $?
//--> echoes
If you execute a binary inside a bash script, and what your script to "forward" the exit code of that binary, than simply write: 如果您在bash脚本中执行二进制文件,然后执行脚本来“转发”该二进制文件的退出代码,则只需编写以下代码:
#!/bin/bash
./your_bin
exit $?
A side-note: returning random ints from a program isn't the greatest of ideas. 旁注:从程序中返回随机整数并不是最好的主意。 exit codes mean something.
退出代码意味着某种意义。 That's why the C standard lib defines 2 macro's:
这就是C标准库定义2个宏的原因:
printf("%d vs %d\n",
EXIT_SUCCESS
EXIT_FAILURE
);
Guess what, EXIT_SUCCESS
shows up as 0, EXIT_FAILURE
is 1. 猜猜是什么,
EXIT_SUCCESS
显示为0, EXIT_FAILURE
为1。
If you want to get the exit value of your c programm, start your c programm also in the .sh file, and then make echo $? 如果要获取c程序的退出值,请同时在.sh文件中启动c程序,然后使echo $?。
./c_prog
echo $?
The value of $? $的价值? is the exit-value of the last command.
是最后一个命令的退出值。 If you start your bash script, which contain only echo $?, they don't have a last command.
如果您启动仅包含echo $?的bash脚本,则它们没有最后一个命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.