Bash
Bash 數組只執行第一個索引
我正在使用執行 Ubuntu 18.01 LTS 的伺服器,並且正在嘗試自動備份多個虛擬機。
我有一個數組中的 VM 名稱,然後是一個 for 循環來關閉、備份然後重新啟動每個 VM。我周末跑了這個,今天進來了,所有命令似乎都執行了,但只針對數組的第一個索引,腳本沒有退出。
這是我的腳本。
#!/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
事實證明,該
VBoxHeadless
命令將每個 VM 作為前台程序啟動,因此循環的執行不會繼續到下一個 VM,直到前一個 VM 退出。對於腳本的重啟部分,我必須使用 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
參考: