1

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.

Nick
  • 4,503
  • 29
  • 69
  • 97

3 Answers3

2

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` ]
Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151
2

You can check return value of grep -q if you don't need grep results. It returns 0 if something matched.

if virsh list | grep -q MediaWiki
then
    echo "The MediaWiki VM is Running!"
else
    echo "Not Running!"
fi
wRAR
  • 292
  • 1
  • 6
0

one thing to keep in mind is that if your command returns null, or "", then you want to use the old DOS trick for comparing nulls:

#!/bin/sh
foo=`<command stuff here>`
if [ "X$foo" == "X" ] 
        then 
                echo "returned null"
        else
                echo "return positive"
fi

Check out the scripting guide

Greeblesnort
  • 1,759
  • 8
  • 10