11

I'm trying to create a function in a shell script that takes a command and executes it using eval, and then does some post-processing based on the success of the command. Unfortunately the code is not behaving as I would expect. Here's what I have:

#!/bin/sh

...

function run_cmd()
{
        # $1 = build cmd

        typeset cmd="$1"
        typeset ret_code

        eval $cmd
        ret_code=$?

        if [ $ret_code == 0 ]
        then
                # Process Success
        else
                # Process Failure
        fi

}

run_cmd "xcodebuild -target \"blah\" -configuration Debug"

When the command ($cmd) succeeds, it works fine. When the command fails ( compilation error, for instance ), the script automatically exits before I can process the failure. Is there a way I can prevent eval from exiting, or is there a different approach I can take that will allow me achieve my desired behavior?

2
  • 2
    there should be no automatic exit unless you have set -e somewhere in your script. If you have it, set +e will disable it. Jan 17, 2013 at 22:20
  • sigh I had set -o errexit lingering at the top of the caller script. Thanks for pointing that out.
    – Jeff
    Jan 17, 2013 at 22:55

1 Answer 1

19

The script should only exit if you have set -e somewhere in the script, so I'll assume that is the case. A simpler way to write the function which will prevent set -e from triggering an automatic exit is to do:

run_cmd() {
        if eval "$@"; then
                # Process Success
        else
                # Process Failure
        fi
}

Note that function is non-portable when defining the function, and redundant if () are also used.

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.