View exit code of a program (After the program exited)

use*_*541 0 linux shell

Lets say a program that outputs a zero in case of success, or 1 in case of failure, like this:

main () {
    if (task_success())
        return 0;
    else
        return 1;
}
Run Code Online (Sandbox Code Playgroud)

Similar with Python, if you execute exit(0) or exit(1) to indicate the result of running a script. How do you know what the program outputs when you run it in shell. I tried this:

./myprog 2> out
Run Code Online (Sandbox Code Playgroud)

but I do not get the result in the file.

Avi*_*mka 5

There's a difference between an output of a command, and the exit code of a command.

What you ran ./myprog 2> out captures the stderr of the command and not the exit code as you showed above.

If you want to check the exit code of the a program in bash/shell you need to use the $? operator which captures the last command exit code.

For example:

./myprog 2> out
echo $?
Run Code Online (Sandbox Code Playgroud)

Will give you the exit code of the command.

顺便说一句,为了捕获命令的输出,您可能需要使用捕获stdout和捕获stderr1作为重定向。12