Bash 数组只执行第一个索引

Bash 数组只执行第一个索引

我正在使用运行 Ubuntu 18.01 LTS 的服务器,并且我正在尝试自动备份多个虚拟机。

我将虚拟机名称放在一个数组中,然后使用 for 循环来关闭、备份并重新启动每个虚拟机。我周末运行了这个,今天进来,所有命令似乎都已运行,但仅针对数组的第一个索引,并且脚本不退出。

这是我的脚本。

#!/bin/bash
######################
#
# Shut down and back up select VMs
#
#####################

#make new date formatted directory
sudo mkdir /mnt/md1/VirtualMachines/bak/$(date +%Y_%m_%d) |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt;
sudo chown bvserv /mnt/md1/VirtualMachines/bak/$(date +%Y_%m_%d) |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt;

#Array of VMs
declare -a VM=("Win-10-POS-1" "Win-10-POS-2" "Desktop_Neil")

#loop through array of VMs
for i in "${VM[@]}"
do
# Shut down virtual machine
sudo -u bvserv VBoxManage controlvm "$i" poweroff |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt;
# Export virtual machine to dated file
sudo -u bvserv VBoxManage export "$i" -o /mnt/md1/VirtualMachines/bak/$(date +%Y_%m_%d)/"$i".ova |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt;
# Restart virtual machine
sudo -u bvserv VBoxHeadless --startvm "$i" |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt
done

答案1

问题在于该VBoxHeadless命令将每个虚拟机作为前台进程启动,因此循环的执行不会继续到下一个虚拟机,直到前一个虚拟机退出。

对于脚本的重新启动部分,我必须使用 VBoxManage 而不是 VBoxHeadless 来启动机器。进行更改后,一切正常。这是更新后的脚本,现在加载外部数组以供参考。

#!/bin/bash
######################
#
# Shut down and back up select VMs
#
#####################

#make new date formatted directory
sudo mkdir /mnt/md1/VirtualMachines/bak/$(date +%Y_%m_%d) |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt;
sudo chown bvserv /mnt/md1/VirtualMachines/bak/$(date +%Y_%m_%d) |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt;

#Read array of virtual machines from file
readarray -t VM < /mnt/md1/VirtualMachines/auto-start_list.txt

#loop through array of VMs
for i in "${VM[@]}"
do
# Shut down virtual machine
sudo -u bvserv VBoxManage controlvm "$i" poweroff |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt;
# Export virtual machine to dated file
sudo -u bvserv VBoxManage export "$i" -o /mnt/md1/VirtualMachines/bak/$(date +%Y_%m_%d)/"$i".ova |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt;
# Restart virtual machine
sudo -u bvserv VBoxManage startvm "$i" --type headless |& tee -a /mnt/md1/Scripts/log_vboxBak_$(date +%Y_%m_%d).txt
#echo "$i"
done

参考:

相关内容