0

嗨,我正在使用此脚本在执行操作之前检查 vm 是否正在运行

#!/bin/bash
vm="PopOS VNC"
vmstate=$(virsh list --all | grep " $vm " | awk '{ print $3}')

if [ "$vmstate" == "x" ] || [ "$vmstate" != "running" ]
then
    echo "VM is shut down" 
else
    echo "VM is running!"
fi

当 vm 正在运行但 vm 变量有空格时,脚本无法按预期工作

vm="PopOS VNC"

随着虚拟机运行,vmstate 的值是“VNC”而不是“运行”,如预期的那样

随着 vm 停止值仍然是“VNC”

但是,对于没有空格的 vm 名称,它可以按预期工作(如下所示)

vm="CentOS10"

随着 VM 的运行,vmstate 的值按预期“运行”。

虚拟机关闭后,该值按预期“关闭”

请有人告诉我如何让它与名称中有空格的虚拟机一起使用。

非常感谢 :)

编辑 virsh list --all 的输出

 Id   Name                  State
--------------------------------------
 -    Big Sur               shut off
 -    True NAS              shut off
 -    CentOS10              shut off
 -    Debian-10             shut off
 -    dos_6.22              shut off
 -    Windows 95            shut off
 -    Gparted Live          shut off
 -    Popos AMD gpu         shut off
 -    PopOS VNC             shut off
 -    OpenSUSE              shut off
 -    Windows 98 VNC        shut off
 -    OpenSUSE2             shut off
 -    pfSense               shut off

使用 set x 输出脚本

+ vm='PopOS VNC'
++ virsh list --all
++ awk '{ print $3}'
++ grep ' PopOS VNC '
+ vmstate=VNC
+ '[' VNC == x ']'
+ '[' VNC '!=' running ']'
+ echo 'VM is shut down'
VM is shut down
+ set +x
4

1 回答 1

0

I assume there is a problem with quotes " or ' or both.

In order to debug your script and see the actual commands expansion by the shell I use set -x to start commands echo and set +x to stop command echo.

Suggest to run the following script:

#!/bin/bash
set -x
vm="PopOS VNC"
vmstate=$(virsh list --all | grep " $vm " | awk '{ print $3}')

if [ "$vmstate" == "x" ] || [ "$vmstate" != "running" ]
then
    echo "VM is shut down" 
else
    echo "VM is running!"
fi
set +x

I assume there is problem with variable expansion in grep " $vm "

Please post your results in the post.

In addition remember that awk default field separator is . When your $vm is 2 worded the required awk field is shifted right to: awk '{ print $4}', and if the $vm is 3 worded the required awk field is awk '{ print $5}'.

Maybe it is better to take the last word awk '{ print $NF}'

Or to take one word before the last word awk '{ print $(NF - 1)}'

于 2022-02-20T19:08:02.593 回答