I am trying to write a function in a bash script which accepts a command as an argument, executes the command -- AND -- if the command non-zero exited, abort the script:

file: command_wrapper.sh

#!/usr/bin/env bash

function exec_cmd() {
    local command=${1}
    $command || exit            # run the command if $? is 1 exit
    if [[ $? -eq 1 ]]           # AGAIN if $? is 1 exit
        echo "command failed"

    return 0

exec_cmd "grep -R somsomeoemoem ."      # call the function, passing a 
                                        # command that will exit with 1

echo "rest of script running"

call it:

% ./command_wrapper.sh
./command_wrapper.sh:exec_cmd "grep -R somethingyouwillneverfind ."
rest of script running

the script carries on after the function is run with a command that non-zero exits - why?
How can I get this command to error exit when $command fails?

1 Answer 1


Your function works as designed but the issue is your assumption is incorrect. grep -R somsomeoemoem . doesn't exit in error.

Try with this command to see the function exiting:

exec_cmd "false"
  • I think my grep is returning 1. when I run this on the command line % grep -R slkdjfsldkjf . ; echo $? output is: 1 (im using GNU grep) Mar 26, 2017 at 21:59
  • What happens in your case with exec_cmd "false" ?
    – jlliagre
    Mar 26, 2017 at 22:00
  • 1
    gah, actually, I think grep is returning 0, but for an embarrassing reason, it IS finding the text somethingyouwillneverfind - its finding it in its own source code file! Mar 26, 2017 at 22:02
  • Ah, you are right :-)
    – jlliagre
    Mar 26, 2017 at 22:02
  • ah yes, when I use exec_cmd "false" it behaves as expected. Thanks for pointing out the false command, I will use that from now on! Mar 26, 2017 at 22:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .