LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Repeat if loop in bash script (https://www.linuxquestions.org/questions/linux-newbie-8/repeat-if-loop-in-bash-script-4175484579/)

linson_85 11-14-2013 11:19 AM

Repeat if loop in bash script
 
Hello,

I'm trying to setup a bash script for creating KVM guests. What I'm trying to setup is, i need to verify whether VM name exists on the host already first. If with no such name, then create the VM. To make it clear I have following VMs created on my host

Output of virt list -all

Id Name State
----------------------------------------------------
3 ffDeb64 running
5 Deb-6-32 running
6 Clust-VM01 running
7 Clust-VM02 running

----------------------------------------------------

So I'm trying to setup a script that will ask to enter the desired name first. If such name exists, then it should prompt again to enter the name. If such name doesn't exists, the script will create the VM. The intention is to use unique VM name during creation


Script details is as follows

]# cat createvm.sh
#!/bin/bash
echo -n " Enter the name : "; read VMname #line1
if [[ "$(cat virt-list.sh |awk '{print $2}'|grep $VMname)" == "$VMname" ]] #line2
then #line3
echo "The name $VMname exists" #line4
else #line5
echo "Proceed with further ..." #line6
fi #line7




Content of file virt-list.sh is as follows

]# cat virt-list.sh
Id Name State
----------------------------------------------------
3 ffDeb64 running
5 Deb-6-32 running
6 Clust-VM01 running
7 Clust-VM02 running


So, I want the script go to line1 when it execute the line4

Which means if VM name exists, I want the script to prompt to enter the VM name again ( which suppose to be unique name )

Whats the best and easier way to achieve this ?
Any help ?

druuna 11-14-2013 11:47 AM

Have a look at this:
Code:

#!/bin/bash

while true
do
  read -r -p "Enter the name : " VMname

  if ! $(virsh list --all | grep -q "\b$VMname\b")
  then
    break
  else
    echo "Oops, name exists."
  fi
done

echo "we can continue with the script"


linson_85 11-14-2013 08:19 PM

Thanks druuna.

Thats what I needed. Much appreciated.


All times are GMT -5. The time now is 05:29 AM.