tags:

views:

109

answers:

5

When our server comes up we need to check a file to see how the server is configured.

We want to search for the following string inside our /etc/aws/hosts.conf file:

MYSQL_ROLE=master

Then, we want to test whether that string exists and use an if/else statement to run one of two options depending on whether the string exists or not.

What is the BASH syntax for the if statement?

if [ ????? ]; then
  #do one thing
else
  #do another thing
fi
+4  A: 

if takes a command and checks its return value. [ is just a command.

if grep -q ...
then
  ....
else
  ....
fi
Ignacio Vazquez-Abrams
+1  A: 

Try:

if [ -n "`grep \"MYSQL_ROLE=master\" /etc/aws/hosts.conf`" ]; then
bta
+4  A: 
Roger Pate
Thanks! Works like a charm.
A: 

just use bash

while read -r line
do
  case "$line" in
    *MYSQL_ROLE=master*)
       echo "do your stuff";;
    *) echo "doesn't exist";;      
  esac
done <"/etc/aws/hosts.conf"
ghostdog74
A: 

Note that, for PIPE being any command or sequence of commands, then:

if PIPE ; then
  # do one thing if PIPE returned with zero status ($?=0)
else 
  # do another thing if PIPE returned with non-zero status ($?!=0), e.g. error
fi 

For the record, [ expr ] is a shell builtin shorthand for test expr.

Since grep returns with status 0 in case of a match, and non-zero status in case of no matches, you can use:

if grep -lq '^MYSQL_ROLE=master' ; then 
  # do one thing 
else 
  # do another thing 
fi 

Note the use of -l which only cares about the file having at least one match (so that grep returns as soon as it finds one match, without needlessly continuing to parse the input file.)

vladr