Search code examples
bashechobash-function

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


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?


Solution

  • 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