Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Check output of command

Tags:

linux

bash

I need to check the output of apachectl configtest in a bash script and restart if everything looks good without outputting the command to the screen

var =sudo apachectl configtest

If var contains "Syntax OK" then

sudo apachectl graceful

How to do it?

like image 325
dev810vm Avatar asked May 06 '17 02:05

dev810vm


3 Answers

The bash syntax you are after in your first command is probably "command substitution":

VAR=$(sudo apachectl configtest)

VAR will contain the output of the commandline.

But, if you just want to know if the output contains "Syntax OK", do it like this:

sudo apachectl configtest | grep -q "Syntax OK" && proceed || handle-error

where proceed and handle-error are your functions that handle your ok and error cases, respectively.

(Note the -q option of grep to hide the output of the apachectl command.)

like image 45
Ville Oikarinen Avatar answered Sep 20 '22 15:09

Ville Oikarinen


I know this is the old thread and the question doesn't suit this particular site. Anyway, looking for the same question, this page was shown as the first search result. So, I am posting here my final solution, for a reference.

configtestResult=$(sudo apachectl configtest 2>&1)

if [ "$configtestResult" != "Syntax OK" ]; then
    echo "apachectl configtest returned the error: $configtestResult";
    exit 1;
else
    sudo apachectl graceful
fi

This thread contains a clue regarding catching configtest output.

like image 140
Y. E. Avatar answered Sep 17 '22 15:09

Y. E.


As @slm says on the link, you can used -q for quiet. That way it don't output the command on the screen. Make sure there no space between the variable, the '=' and the command as @William Pursell says here. After that test if your variable contains "Syntax OK". The following code snippet does that.

var1=$(sudo apachectl configtest)

if echo $var1 | grep -q "Syntax OK"; then
    sudo apachectl graceful
fi
like image 45
berrytchaks Avatar answered Sep 19 '22 15:09

berrytchaks