GRme
GRme

Reputation: 2757

Getting the output of the previous command in shell script

I have the following shell script:

#!/usr/bin/env sh
./node_modules/.bin/nightwatch --env chrome --tag=enabled
exit 0

The nightwatch command always returns the exit code 1, doen’t matter if the nightwatch tests will fail or pass. So, I want to check if the console output of this command contains a specific string (maybe failed) to handle on it and to return a right exit code with the shell script.

The only requirement I have is, that the nightwatch command output is visible on console because we will need it because of debugging reasons.

I want to do something like this (pseudo code):

#!/usr/bin/env sh
./node_modules/.bin/nightwatch --env chrome --tag=enabled
if lastOutput.contains("failed"); then
  exit 1
else
  exit 0
fi

Upvotes: 1

Views: 4007

Answers (2)

beau
beau

Reputation: 16

Plenty of more efficient ways to go about this, but according to your pseudocode:

#!/usr/bin/env sh
lastOutput=$(./node_modules/.bin/nightwatch --env chrome --tag=enabled)
if [[ $lastOutput = *"failed"* ]]; then
  exit 1
else
  exit 0
fi

Upvotes: 0

Inian
Inian

Reputation: 85600

Since you are running this on the POSIX bourne shell sh, you could do a comparison of the command output with the [ operator or the case construct

case "$(./node_modules/.bin/nightwatch --env chrome --tag=enabled)" in
  *failed*)  exit 1;;
   *) exit 0 ;;
esac

or use the return code of grep and asking it to be silent with the -q flag set

if ./node_modules/.bin/nightwatch --env chrome --tag=enabled | grep -q failed; then
    exit 1 
else
    exit 0
fi

Upvotes: 2

Related Questions