简体   繁体   中英

echo $? behaves differently

I have this C program:

int main() { return 10; }

After running this when I write echo $? in the terminal its prints 10 .

Now suppose I have a .sh file:

echo $?

After running the C program if I run the .sh file it prints 0 .

Why?

Simple: the .sh file gets executed by bash, or some other shell. That binary ( /bin/bash or wherever it is) executes the script and then exits. If the shell binary exits successfuly, it returns 0 to the system
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). So echo $? probably echoes the return value of another process that the executing shell instance ran (login, or whatever...)

the command 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. Your .sh file, though is executed by another binary, that returns 0 (upon success), hence echo $? shows 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:

#!/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:

printf("%d vs %d\n",
    EXIT_SUCCESS
    EXIT_FAILURE
);

Guess what, EXIT_SUCCESS shows up as 0, EXIT_FAILURE is 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_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM