Search code examples
thoughtworks-go

Fail build in Go when custom command fails


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?


Solution

  • 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 $?