Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exit code for eval command in sh

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?

like image 765
Jeff Avatar asked Jan 17 '13 22:01

Jeff


People also ask

How do I find my exit code?

To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.

How do I find exit code from previous command?

Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.

What does eval return bash?

`eval` returns an exit status code after executing the command. `eval` returns 0 as exit status code if no argument is provided or only null argument is provided.

What is exit code in shell script?

Exit Codes. Exit codes are a number between 0 and 255, which is returned by any Unix command when it returns control to its parent process. Other numbers can be used, but these are treated modulo 256, so exit -10 is equivalent to exit 246 , and exit 257 is equivalent to exit 1 .


1 Answers

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.

like image 112
William Pursell Avatar answered Sep 18 '22 17:09

William Pursell