How do I send a command with a message to echo on success to a bash function?

395 Views Asked by At

I've written a function to check if a command executed successfully, and if not, throw an error.

assert_success () {
    "$1"
    if [[ $? == 0 ]]; then
        echo "$2"
    fi
}

Say I have the following command to execute with the given error :

assert_success <command> <error_message>

So basically, something like the following :

assert_success $(mkdir blah) "This worked"

However, I get a.sh: line 3: This worked: command not found

How do I get the echo to work correctly here?

2

There are 2 best solutions below

0
On BEST ANSWER

Problem is in this call:

assert_success $(mkdir blah) "This worked"`

you are passing output of mkdir command, not the mkdir command itself. And since output of mkdir is empty and it is unquoted "This worked" becomes $1 inside your function and you get error: This worked: command not found

I suggest you have your function like this:

assert_success () {
   msg="$1"
   shift
   if $@; then
      echo "$msg"
   fi
}

and call this function as:

assert_success "This worked" mkdir blah
0
On

Aside from the issues discussed in the link in my comment, there is no need for such a function. It's shorter to simply run your command, then use the && operator to print the success message. Compare

mkdir blah && echo "This worked"

with either

assert_success "mkdir blah" "This worked"

or anubhava's solution

assert_success "This worked" mkdir blah