bashshellprocessexit-codereturn-code

How to get return code of command run before bash script?


$ beep; echo $?

Command 'beep' not found, but can be installed with:

apt install beep
Please ask your administrator.

127
$ cat test.sh
#!/usr/bin/env bash
echo $?

The expected output of my script should be "127".

Why, then, after executing the bash script in the same manner, the return code printed is not what we expect?

$ beep; ./test.sh

Command 'beep' not found, but can be installed with:

apt install beep
Please ask your administrator.

0

Solution

  • $? is not inherited by child processes.

    You can export it to an environment variable, and check that in the script.

    test.sh:

    #!/usr/bin/env bash
    echo $CODE
    

    then

    beep
    CODE=$? ./test.sh
    

    Or you could pass $? as a script parameter:

    test.sh

    #!/usr/bin/env bash
    echo "$1"
    

    then

    beep; ./test.sh $?