[英]bash scripting and conditional statements
我正在嘗試運行一個簡單的bash腳本,但我正在努力解決如何陷入困境。 任何指針。 循環說。 我想加入一個條件,當gdalinfo無法打開圖像時,它會將該特定文件復制到另一個位置。
for file in `cat path.txt`; do gdalinfo $file;done
在打開圖像時效果很好,並顯示哪些圖像無法打開。
錯誤的代碼是
for file in `cat path.txt`; do gdalinfo $file && echo $file; else cp $file /data/temp
一次又一次-zilion th ...
不要使用類似的結論
for file in `cat path.txt`
要么
for file in `find .....`
for file in `any command what produces filenames`
因為當文件名或路徑包含空格時,代碼將立即BREAK。 切勿將其用於產生文件名的任何命令。 不好的做法。 很壞。 它是錯誤的,錯誤的,錯誤的,不准確的,不精確的,不精確的,錯誤的,錯誤的。
正確的形式是:
for file in some/* #if want/can use filenames directly from the filesystem
要么
find . -print0 | while IFS= read -r -d '' file
或者(如果你確定沒有文件名包含換行符)可以使用
cat path.txt | while read -r file
但是這里的cat
是沒用的,(真的 - 命令只將文件復制到STDOUT 是沒用的)。 您應該改用
while read -r file
do
#whatever
done < path.txt
它更快(不會像每個管道一樣派生一個新進程)。
以上while
旨意填寫corect文件名到變量file
的情況下,當文件名包含空格了。 for
不會 。 期。 UFF。 我的天啊。
出於同樣的原因,使用"$variable_with_filename"
而不是純$variable_with_filename
。 如果文件名包含空格,則任何命令都會誤認為它是兩個文件名。 這可能不是,你想要的......
因此,請將包含文件名的雙引號括起來的所有shell變量括起來。 (不僅是文件名,還包含任何可以包含空格的東西)。 "$variable"
是正確的。
如果我理解正確,那么當gdalinfo
返回錯誤時,您希望將文件復制到/data/temp
。
while read -r file
do
gdalinfo "$file" || cp "$file" /data/temp
done < path.txt
美觀,簡短,安全(至少如果path.txt實際上每行包含一個文件名)。
也許,你想要更多次使用你的腳本,因此不要在里面輸出文件名,而是將腳本保存在表單中
while read -r file
do
gdalinfo "$file" || cp "$file" /data/temp
done
並使用它像:
mygdalinfo < path.txt
更通用...
也許,您只想顯示gdalinfo
返回錯誤的文件名
while read -r file
do
gdalinfo "$file" || printf "$file\n"
done
如果你將printf "$file\\n"
更改為printf "$file\\0"
你可以安全地使用管道中的腳本,所以:
while read -r file
do
gdalinfo "$file" || printf "$file\0"
done
並將其用作例如:
mygdalinfo < path.txt | xargs -0 -J% mv % /tmp/somewhere
Howgh。
你可以說:
for file in `cat path.txt`; do gdalinfo $file || cp $file /data/temp; done
如果gdalinfo無法打開圖像,這會將文件復制到/data/temp
。
如果除了在發生故障時復制文件名之外還要打印文件名,請說:
for file in `cat path.txt`; do gdalinfo $file || (echo $file && cp $file /data/temp); done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.