Reputation: 31
I would like to know how to do this, if for example, when executing a command in a script, retrieve the message linked to this command. For example "AZERTY already exists, please check the error" is the message that comes out after a command (wrong), how do I so that if my BASH script sees this info, tell it to stop the script?
Upvotes: 0
Views: 96
Reputation: 212178
You almost certainly should not check the error message. Instead just do:
cmd || exit
If cmd
fails and writes the message "AZERTY already exists, please check the error" to stderr, then that message will appear and the script will exit with whatever non-zero value cmd
exited with. Some commands return non-zero values that have meaning, and you may want to suppress that (for consistent return values from your script) or change that with something like:
cmd || exit 1
On the other hand, if cmd
is poorly written and returns a zero value when it "fails" (I'm putting that in quotes since a reasonable definition of "fail" is "return non-zero"), then that is a bug in cmd
which should be fixed.
Upvotes: 3
Reputation: 1833
I recommend using strict mode in all your bash scripts. http://redsymbol.net/articles/unofficial-bash-strict-mode/
Basically put this at the top
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
The option you specifically asked about is -e
The set -e option instructs bash to immediately exit if any command [1] has a non-zero exit status. You wouldn't want to set this for your command-line shell, but in a script it's massively helpful. In all widely used general-purpose programming languages, an unhandled runtime error - whether that's a thrown exception in Java, or a segmentation fault in C, or a syntax error in Python - immediately halts execution of the program; subsequent lines are not executed.
Upvotes: 1
Reputation: 21666
if ./command | grep -q 'AZERTY already exists, please check the error'; then
echo "Error found, exiting"
exit 1
fi
Upvotes: 0