Bash 擴充數組,讓它只使用一個元素

Bash 擴充數組,讓它只使用一個元素

我的簡單 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`)

請注意,如果檔案名稱包含空格,它可能會中斷。

相關內容