4

I have this conditional in a script:

if [[ "${SUMAN_ENV}" != "local" ]]; then
 ./suman.sh $@  # run this script instead
 # need to exit here
fi

if the condition is met, I'd like to run another script instead.

Is the best way to do this just to do this:

if [[ "${SUMAN_ENV}" != "local" ]]; then
 ./suman.sh $@
 exit $?  # exit with the code given by the above command
fi

or is there some other way?

  • 7
    Note: You want to use "$@" with quotes to handle arguments with whitespace correctly – ilkkachu Jul 16 '17 at 14:54
12

File hello:

#!/bin/sh
echo "$0"
exec ./world
echo "$0"

File world:

#!/bin/sh
echo "$0"
exit 33 # to have an exit code example                                                                

Run hello:

$ ./hello 
./hello
./world
$ echo $?
33

After hello runs world via exec and world finishes, the remainder of hello is not executed. The exit code is the one of world.

  • 2
    exec replaces the currently running process with the one specified. The PID is unchanged. Most of the resources for the original process are released. – CSM Jul 16 '17 at 14:12
  • @yeti what is exit 33 ? Isn't exit enough ? – GypsyCosmonaut Jul 16 '17 at 15:08
  • 3
    @GypsyCosmonaut ... exit would have been enough but in the question's snippets the 1st script explicitely exits with the exit value of the called 2nd script. So I wanted the 2nd one in my example have a different exit value than the 1st one to have distinguishable values. (No purple magic included there. No explicit exit would be ok too...) – yeti Jul 16 '17 at 15:15
  • So using exec is the key thing here I guess. – Alexander Mills Jul 16 '17 at 20:15
  • So using exec is the key thing here I guess??? – Alexander Mills Oct 14 '17 at 4:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.