I'm using Go's custom command to execute a shell script. The problem is, if the script fails for any reason, the build still succeeds. How do I fail the build if something goes wrong in my shell script?
-
Did my answer work for you? – jeremyjjbrown Mar 10 '15 at 02:09
2 Answers
Arrange the logic in your script so that if the script fails it exits with an exit code >= 1
#!/bin/bash
N=0
#do your logic here and increment N for each failure.
ls /non/existent/dir || {
echo "can't ls /non/existent/dir"
N=$((N+1))
}
#do something else
echo "we had $N errors"
exit N
alternatively if you want to fail fast
#!/bin/bash
ls /non/existent/dir || {
echo "can't ls /non/existent/dir"
exit 1
}
For each shell cmd you can see the exit code with...
echo $?

- 7,772
- 5
- 43
- 55
-
Nice solution, but... I had this issue right now, and even if I have an empty script with just shebang and `exit 1`, it still succeeds... Having the agent on this PC, I see it fire up the script in CYGWIN as expected, but could it be that this detour somewhere swallows the exit code? – helmesjo May 21 '17 at 12:06
The easiest way to go would be to add either set -e
at the top of the script or change the shebang to #!/bin/bash -e
. -e
will cause bash to exit immediately (with an error) after any[0] command fails. As an aside I suggest adding -u
as well to catch undefined variable use.
[0] It's a little more complicated than that -- it actually only exits if a command fails if that command's result is not tested in the script. See the bash man page for (extensive) details that may differ depending on your specific platform.
See also: "Aborting a shell script if any command returns a non-zero value?" at https://stackoverflow.com/a/4346420/11638666