Bash – grep in bash script + Jenkins


I have a grep command that works in a bash script:

if grep 'stackoverflow' outFile.txt; then
 exit 1

This works fine when run on my host. When I call this from a Jenkins build step however, it exits 0 everytime, not seeing 'stackoverflow'. What is going wrong?

Best Solution

Add the following line as the first line in your "Execute Shell" command


grep command exits with a non zero code when it does not find match and that causes jenkins to mark the job as failed. See Below.

In the help section of "Execute Shell"

Runs a shell script (defaults to sh, but this is configurable) for building the project. The script will be run with the workspace as the current directory. Type in the contents of your shell script. If your shell script has no header line like #!/bin/sh —, then the shell configured system-wide will be used, but you can also use the header line to write script in another language (like #!/bin/perl) or control the options that shell uses.

By default, the shell will be invoked with the "-ex" option. So all of the commands are printed before being executed, and the build is considered a failure if any of the commands exits with a non-zero exit code. Again, add the #!/bin/... line to change this behavior.

As a best practice, try not to put a long shell script in here. Instead, consider adding the shell script in SCM and simply call that shell script from Jenkins (via bash -ex or something like that), so that you can track changes in your shell script.