Shell Script: How to turn “virsh list | grep MediaWiki” into an if condition

grepscriptingshell

I'm trying to determine if a given Virtual Machine is running using a shell script.

The command "virsh list | grep MediaWiki", when run manually, returns one line if the Virtual Machine is running, and returns nothing when it's not.

I'm trying to use:

if [`virsh list | grep MediaWiki` !== ""]
then
        echo "The MediaWiki VM is Running!"
else
        echo "Not Running!"
fi

But I don't think I've got the syntax quite right. With the above code, it claims the machine is running whether it is or not.

Best Answer

You have an exclamation mark followed by two equal signs for "not equal". It should be "!=". Also there needs to be a space after the left square bracket and one before the right square bracket. Also, to test against a null string like that, you have to use double square brackets. The preferred way to do command substitution is with $() instead of backticks.

if [[ $(virsh list | grep MediaWiki) != "" ]]

This all presumes that you're using a shell like Bash that supports these features. If not then this should work:

if [ `virsh list | grep MediaWiki` ]