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?
Problem is in this call:
you are passing output of
mkdir
command, not themkdir
command itself. And since output ofmkdir
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:
and call this function as: