rzenks rzenks - 6 months ago 11
Bash Question

How can i check specific server running or not(using virsh commands), before I start | restart it?

I'm trying to restart, start, shutdown a specific virtual machine.
Here, at first I want to check if the virtual machine is already in required state or not before I run the script.

These are the list of VMs.

[root@demohost05 ~]# virsh list --all
Id Name State
----------------------------------------------------
5 OwnCloud01 running
6 OwnCloud02 running
7 SiteMon running
- vmtest shut off


I want to check if vmtest is runnnig or not before I implement

virsh start vmtest


How can check the status using if condition in shell script ?

How can I avoid to enter password when I've to use sudo command.

sudo virsh start vmtest


I also tried to give root permission using

sudo -i
virsh start vmtest


But script ends without implementing 2nd line.
How can I use both commands in same script file?

if [conditions]
then
{

}
fi


I couldnt figure out how to check conditions for such scripts.

Thank you.

Answer

Try this:


tmp=$(virsh list --all | grep " vmtest " | awk '{ print $3}')
if ([ "x$tmp" == "x" ] || [ "x$tmp" != "xrunning" ])
then
    echo "VM does not exist or is shut down!"
    # Try additional commands here...
else
    echo "VM is running!"
fi