0

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;
}

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

but I do not get the result in the file.

user1135541
  • 1,781
  • 3
  • 19
  • 41
  • Use a print command in program. – Ajay Gupta Mar 06 '16 at 07:40
  • Imagine you are a program. Your *output* is things you have said and written during your life. Your *exit code* is whether you go to heaven or to hell after you die. – n. m. could be an AI Mar 06 '16 at 10:37
  • Possible duplicate of [Exit Shell Script Based on Process Exit Code](http://stackoverflow.com/questions/90418/exit-shell-script-based-on-process-exit-code) – tod Mar 06 '16 at 12:59

2 Answers2

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 $?

Will give you the exit code of the command.

BTW, For capturing the output of a command, you may need to use 1 as your redirect where 1 captures stdout and 2 captures stderr.

Avihoo Mamka
  • 4,656
  • 3
  • 31
  • 44
0

The returnvalue of a command is stored in $?. When you want to do something with the returncode, it is best to store it in a variable before you call another command. The other command will set a new returncode in $?.
In the next code the echo will reset the value of $?.

rm this_file_doesnt_exist
echo "First time $? displays the rm result"
echo "Second time $? displays the echo result"
rm this_file_doesnt_exist
returnvalue_rm=$?
echo "rm returned with ${returnvalue}"
echo "rm returned with ${returnvalue}"

When you are interested in stdout/stderr as well, you can redirect them to a file. You can also capture them in a shell variable and do something with it:

my_output=$(./myprog 2>&1)
returnvalue_myprog=$?
echo "Use double quotes when you want to show the ${my_output} in an echo."
case ${returnvalue_myprog} in
   0) echo "Finally my_prog is working"
      ;;
   1) echo "Retval 1, something you give in your program like input not found"
      ;;
   *) echo "Unexpected returnvalue ${returnvalue_myprog}, errors in output are:"
      echo "${my_output}" | grep -i "Error"
      ;;
esac
Walter A
  • 19,067
  • 2
  • 23
  • 43