Home > Software design >  Check if a String Exists in Command Output
Check if a String Exists in Command Output

Time:10-14

I'm working on a Bash script which checks the output of a few different commands and echo's information based what is contained in the output. It is complete minus one command I and I could use some additional insight into this.

This is for an Nginx environment. So the command is just simple: nginx -t (to test Nginx configuration). It's easy to run that command on it's own so it's not necessarily required in the script but it got me wondering how to achieve this for the sake of my own knowledge.

I've tried a few different variations of the following (all to no avail):

if [[ $(nginx -t >/dev/null 2>&1) == *"Success"* ]]; then echo "pass"; else echo "FAIL"; fi;

Then this next version, but that outputs:

# if [[ $(nginx -t >/dev/null 2>&1) == *"Success"* ]]; then echo "PASS"; else echo "| FAIL"; fi;
FAIL

Even though it is passing. The other version I had outputs a success even though it is failing.

On this particular server environment nginx -t has a multi line output but the last lines are all I care about:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

The logic is simply, check for the existence of the "syntax is ok" or "test is successful" string then echo the output based on that. But I can't seem to get it to happen XD

Bash and Nginx experts, could you help me out with me with a working example? :)

CodePudding user response:

In ...

if [[ $(nginx -t >/dev/null 2>&1) == *"Success"* ]]; then echo "pass"; else echo "FAIL"; fi;

... the >/dev/null part suppresses the command's standard output by redirecting it to /dev/null, leaving nothing to capture. The 2>&1 part makes the standard error go to the same place, though it would not otherwise have been captured anyway.

Supposing that you indeed do want to test nginx's output rather than its exit status, and based on your description of the logic you want, it appears that something like this would be suitable:

if nginx -t 2>&1 | tail -n2 | grep -E -q 'syntax is ok|test is successful'; then
  echo pass
else
  echo FAIL
fi

The tail command filters out all but the last two lines of nginx's output to make things a little easier on grep and reduce the scope for false positives. The grep checks whether the remaining output contains at least one of the two specified strings, and returns a success status if and only if it does.

  • Related