Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test (in one line) if command output contains a certain string?

Tags:

bash

In one line of bash, how do I return an exit status of 0 when the output of /usr/local/bin/monit --version doesn't contain exactly 5.5 and an exit status of 1 when it does?

like image 252
Dane O'Connor Avatar asked Sep 11 '12 18:09

Dane O'Connor


People also ask

How do you check if a variable contains a string?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.

How do you check if a file contains a string in Unix?

Just run the command directly. Add -q option when you don't need the string displayed when it was found. The grep command returns 0 or 1 in the exit code depending on the result of search.


2 Answers

! /usr/local/bin/monit --version | grep -q 5.5 

(grep returns an exit-status of 0 if it finds a match, and 1 otherwise. The -q option, "quiet", tells it not to print any match it finds; in other words, it tells grep that the only thing you want is its return-value. The ! at the beginning inverts the exit-status of the whole pipeline.)

Edited to add: Alternatively, if you want to do this in "pure Bash" (rather than calling grep), you can write:

[[ $(/usr/local/bin/monit --version) != *5.5* ]] 

([[...]] is explained in §3.2.4.2 "Conditional Constructs" of the Bash Reference Manual. *5.5* is just like in fileglobs: zero or more characters, plus 5.5, plus zero or more characters.)

like image 122
ruakh Avatar answered Sep 19 '22 12:09

ruakh


[ $(/usr/local/bin/monit --version) == "5.5" ]  

eg-1: check for success

[ $(/usr/local/bin/monit --version) == "5.5" ] && echo "OK" 

eg-2: check for failure

    [ $(/usr/local/bin/monit --version) == "5.5" ] || echo "NOT OK" 

or, to just check if the output contains 5.5:

[[ $(/usr/local/bin/monit --version) =~ "5.5" ]] || echo "NOT OK" 
like image 26
perreal Avatar answered Sep 20 '22 12:09

perreal