notacorn
notacorn

Reputation: 4109

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

Upvotes: 1

Views: 44

Answers (1)

Barmar
Barmar

Reputation: 782166

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

Upvotes: 3

Related Questions