Wednesday, November 26, 2014

acting on command output

you can catch/parse the output of a command and act upon it.

a basic example below is for mysql service status.

[[ $( { mysql status >/dev/null; } |& grep "Can't connect" | wc -l ) -eq "1" ]] && service mysql start



it's basically a one liner condition. the first part before the && should return non-false for the second part to execute. if service is not recognised

when we try

echo $( { mysql status >/dev/null; } |& grep "denied" | wc -l )

>1


if you have a mysql server running, it will need a user/password to run the mysql command. And since we don't supply it, you will get the standart

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

and within that response there's our denied keyword, that we are checking with grep. That output is piped to wc which prints the new line count, and that would be 1 if the server is down. So the equals to 1 is true and the start command is executed. You can call the mysql script under /etc/init.d or /etc/rc.d/init.d instead of service . This kind of execution is good for maintenance and conditional executions.

No comments:

Post a Comment