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?
3 Answers
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.
3 Comments
echo Command failed is not writing an error message. But echo Command failed >&2 should be re-written as echo Command failed >&2 && false. Conventions like this are extremely important and ought to be honored.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.
2 Comments
set -e since it has many pitfalls and its behavior is different across different shells or different versions of the same shell. It is better to explicitly exit than to rely on set -e