Creatorek
Creatorek

Reputation: 9

How to make the sh script return an error code from the executed command?

I wrote a simple script which will prompt pppd to work. I have read in the pppd documentation that it can return an exit code in the range 1-20. I would like my script to return the value of pppd if it is not 0. I tried this way but unfortunately it failed.

myscript.sh:

#!/bin/sh

exec pppd call ${@:-provider}
if [ $? !-eq 0 ]
then
  exit $?
fi

How could i get the exit code from pppd?

Upvotes: 0

Views: 704

Answers (1)

William Pursell
William Pursell

Reputation: 212228

Just do:

#!/bin/sh

pppd call "${@:-provider}" || exit
...

or

if pppd call "${@:-provider}"; then : ; else exit; fi

If pppd fails, the script will exit and the value it returns will be that returned by pppd. (You could explicitly write exit $?, but that is the default value returned by exit when no argument is given and is not necessary.) If pppd succeeds, the script will continue.

The problem with your script (other than the ill-advised usage of exec, which I will mostly ignore) is that calling [ $? -ne 0 ] resets $?. You could re-write your script as:

#!/bin/sh

pppd call "${@:-provider}"
save_val=$?
if ! [ $save_val -eq 0 ]
then
  exit $save_val
fi

but that seems excessively verbose.

Note that in your original script, you would get an error on the line if [ $? !-eq 0 ], since !-eq is not a valid operator. However, you never see that error because your early invocation of exec makes it so that line is never executed.

Upvotes: 2

Related Questions