Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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` ]
share|improve this answer
    
didn't even see that...good catch =) –  Greeblesnort Sep 13 '09 at 4:58
    
Thanks, it's working now! :) –  Nick Sep 13 '09 at 6:41

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
share|improve this answer

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

share|improve this answer
    
Thanks for the link! –  Nick Sep 13 '09 at 6:40
    
quite welcome....pointers to documentation are always free =) –  Greeblesnort Sep 15 '09 at 0:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.