![Bash 擴充數組,讓它只使用一個元素](https://rvso.com/image/1482480/Bash%20%E6%93%B4%E5%85%85%E6%95%B8%E7%B5%84%EF%BC%8C%E8%AE%93%E5%AE%83%E5%8F%AA%E4%BD%BF%E7%94%A8%E4%B8%80%E5%80%8B%E5%85%83%E7%B4%A0.png)
我的簡單 bash 腳本用於獲取 Raspberry Pi 超過一分鐘的映像:
#!/bin/bash
time=`date +"%FT%H_%M_%S"`
imagedir="/root/pilapse/images/"
files=`ssh pi find /home/pi/weatherPi-images/ -type f -mmin +1`
echo -e "\033[1;32mFetching images from Raspberry Pi\033[1;00m"
for currFile in "${files[@]}"; do
echo -e "rsync -a --remove-source-files --info=progress2 -e ssh pi:$currFile $imagedir\n"
done
echo -e "rsync [...]"
這裡只是一個調試用的佔位符。
預期輸出:
rsync -a --remove-source-files --info=progress2 -e ssh pi:/home/pi/weatherPi-images/2016-02-01T13_22_20.jpg /root/pilapse/images/
rsync -a --remove-source-files --info=progress2 -e ssh pi:/home/pi/weatherPi-images/2016-02-01T13_14_07.jpg /root/pilapse/images/
實際輸出:
rsync -a --remove-source-files --info=progress2 -e ssh
horizon:/home/pi/weatherPi-images/2016-02-01T13_22_20.jpg
/home/pi/weatherPi-images/2016-02-01T13_14_07.jpg
/home/pi/weatherPi-images/2016-02-01T13_18_45.jpg
/home/pi/weatherPi-images/2016-02-01T13_13_37.jpg /root/pilapse/images/
不知何故,bash 似乎在這裡擴展了數組,但為什麼呢?根據我的理解,上面的 foreach 迴圈currFile
僅包含一條路徑。
答案1
您沒有建立files
為數組。數組需要括號:
files=(`ssh pi find /home/pi/weatherPi-images/ -type f -mmin +1`)
請注意,如果檔案名稱包含空格,它可能會中斷。