Search code examples
bashexit-code

What's the best way to preserve an exit code or assign it to a variable with Bash?


I'm trying to save the exit code from running psql in a shell script. Assuming the psql command right before this snippet was bad, I'm expecting this snippet to return anything but 1, which it initially does. But when I assign it to exitcode and then echo it, the returned value is a 0...

$ echo $?
    1
$ exitcode=$?
$ echo 'simply'
    simply
$ #echo $?
    0
$ #echo 'coding'
    coding
$ echo $exitcode
    0

I'm trying to get the variable exitcode to print or echo 1 like the first line does. How do I exactly do this?


Solution

  • When you print $? the second time, it's not the exit code of the previous command. You need to assign $? to exitcode immediately before running any other command.

    i.e.

    $ psql
    $ echo $?
        1
    $ exitcode=$?
    

    should be

    $ psql
    $ exitcode=$?
    

    in order to preserve the exit code of psql.