your question looks to me like a typical X-Y problem: your issue is that you want to act when your command failed, and when that happens, it will set the return value to a non zero value. So what you actually want is to use the $?
variable. Here's a generalised example of your use case:
$ ./command
Argh... Failure!
$ echo $?
1
so you could do:
if [ $? -eq 1 ]; then
echo "It failed :("
fi
it's likely you have several return values to descriminate errors, and thus you can check for a value equal to 2
, 3
or 255
instead.
but your shell allows you to do that in a more concise way:
# prints 'it failed :(' only when command's result ($?) is non-null
./command || echo "it failed :("
so for your example you should be able to accomplish it using:
./eqagent add-target target-type=kafka events-servers=localhost:9999 || echo "it failed :("
if your command really only returns the error state using a string (not nice), you can check the exact string using:
output=$(./eqagent add-target target-type=kafka events-servers=localhost:9999)
if [ "$output" == "Equalum agent has returned the following error: The agent target already exists" ]; then
echo "it failed :("
fi
finally you can check for substring inclusion (in case this is not the only output of your program):
error_msg="The agent target already exists"
if [ -z "${output##*$error_msg*}" ] ;then
echo "it failed :("
fi
the above syntax works with most shells (bash, ksh, dash…).
In case you don't get the output you expect in the $output
variable, which is likely if the program prints error on stderr instead of stdout, you can join both outputs using the following trick:
output=$(./eqagent add-target target-type=kafka events-servers=localhost:9999 2>&1)
finally in real use case, you might want a mix of both:
error_msg="The agent target already exists"
output=$(./eqagent add-target target-type=kafka events-servers=localhost:9999)
if [ $? -ne 0 ]; then
echo -n "it failed "
if [ -z "${output##*$error_msg*}" ] ;then
echo "; because target already exists. :-s"
else
echo ":-("
fi
fi