编写bash脚本,不知道如何在谓词中使用多一个函数:
#!/bin/bash
set -x
WAITED=0
registered () {
VBoxManage showvminfo --machinereadable "$1" 2>/dev/null | grep UUID=
}
not_running () {
VBoxManage showvminfo --machinereadable "$1" 2>/dev/null | grep 'VMState="poweroff"'
}
while registered "$1" && not_running "$1" && [ $WAITED -lt 60 ]
do
echo "LOOP"
VBoxManage controlvm "$1" acpipowerbutton 2>/dev/null
((WAITED++))
sleep 1
done
if registered "$1" && ! not_running "$1"
then
echo "POWEROFF"
VBoxManage controlvm "$1" poweroff 2>/dev/null
sleep 1
fi
if registered "$1"
then
echo "UNREG"
VBoxManage unregistervm "$1" --delete 2>/dev/null
fi
输出:
./stop_vm 1b76
+ WAITED=0
+ registered 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep UUID=
UUID="cee02a9a-9a9a-4313-b297-479ca0a41e01"
+ not_running 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep 'VMState="poweroff"'
+ registered 1b76
+ grep UUID=
+ VBoxManage showvminfo --machinereadable 1b76
UUID="cee02a9a-9a9a-4313-b297-479ca0a41e01"
+ not_running 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep 'VMState="poweroff"'
+ echo POWEROFF
POWEROFF
+ VBoxManage controlvm 1b76 poweroff
+ sleep 1
+ WAITED=0
+ registered 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep UUID=
UUID="cee02a9a-9a9a-4313-b297-479ca0a41e01"
+ not_running 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep 'VMState="poweroff"'
VMState="poweroff"
+ '[' 0 -lt 60 ']'
+ echo LOOP
LOOP
+ VBoxManage controlvm 1b76 acpipowerbutton
+ (( WAITED++ ))
+ sleep 1
+ registered 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep UUID=
UUID="cee02a9a-9a9a-4313-b297-479ca0a41e01"
+ echo UNREG
UNREG
+ VBoxManage unregistervm 1b76 --delete
cara@bmserver1-sandbox:~/vm$ + registered 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep UUID=
+ registered 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep UUID=
+ registered 1b76
+ VBoxManage showvminfo --machinereadable 1b76
+ grep UUID=
为什么POWEROFF在LOOP之前出现?没有外环。使用多个函数编写谓词的正确方法是什么?
答案 0 :(得分:0)
问题可能是由于VBox系统在执行" LOOP"中的while
循环体时递归调用脚本引起的。你的代码部分。如果是这种情况,那么您需要重新编写脚本以避免递归(使用某种互斥机制),或者在另一个脚本中执行所需的操作。
你应该引用你的位置参数的扩展(比如"$1"
),你对return $?
的使用是多余的(一个函数,留给它自己,总是返回执行的最后一个语句的返回码)在退出该功能之前)。