Bash は 1 つの要素だけを使用するべき配列を拡張します

Bash は 1 つの要素だけを使用するべき配列を拡張します

1 分以上前の Raspberry Pi の画像を取得するための簡単な bash スクリプト:

#!/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 ループにはcurrFile1 つのパスしか含まれていません。

答え1

files配列として作成しませんでした。配列には括弧が必要です:

files=(`ssh pi find /home/pi/weatherPi-images/ -type f -mmin +1`)

ファイル名に空白が含まれている場合は壊れる可能性があることに注意してください。

関連情報