![Bash は 1 つの要素だけを使用するべき配列を拡張します](https://rvso.com/image/1482480/Bash%20%E3%81%AF%201%20%E3%81%A4%E3%81%AE%E8%A6%81%E7%B4%A0%E3%81%A0%E3%81%91%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B%E3%81%B9%E3%81%8D%E9%85%8D%E5%88%97%E3%82%92%E6%8B%A1%E5%BC%B5%E3%81%97%E3%81%BE%E3%81%99.png)
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 ループにはcurrFile
1 つのパスしか含まれていません。
答え1
files
配列として作成しませんでした。配列には括弧が必要です:
files=(`ssh pi find /home/pi/weatherPi-images/ -type f -mmin +1`)
ファイル名に空白が含まれている場合は壊れる可能性があることに注意してください。