1

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?

gran_profaci
  • 8,087
  • 15
  • 66
  • 99
  • Read [I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050) first. – chepner Dec 03 '15 at 12:34

2 Answers2

1

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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
chepner
  • 497,756
  • 71
  • 530
  • 681