dev810vm
dev810vm

Reputation: 111

Bash: Check output of command

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?

Upvotes: 11

Views: 20058

Answers (3)

Y. E.
Y. E.

Reputation: 784

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.

Upvotes: 10

berrytchaks
berrytchaks

Reputation: 849

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

Upvotes: 3

Ville Oikarinen
Ville Oikarinen

Reputation: 410

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.)

Upvotes: 2

Related Questions