因此,如標題所述,我希望遞歸刪除與用戶給出的命名模式相匹配的所有文件,但僅當文件爲空時纔會刪除。這裏是我的嘗試:Linux bash腳本:根據用戶輸入的文件格式,如果爲空,可以重新刪除文件
#!/bin/bash
_files="$1"
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
[ ! -f "$_files" ] && { echo "Error: $0 no files were found which match given naming structure."; exit 2; }
for f in $(find -name $_files)
do
if [ -s "$f" ]
then
echo "$f has some data."
# do something as file has data
else
echo "$f is empty. Deleting file."
rm $f
fi
done
輸出示例:
./remove_blank.sh *.o*
./Disp_variations_higher_0.o1906168 has some data.
./remove_blank.sh *.e*
./Disp_variations_higher_15.e1906183 is empty. Deleting file.
正如你看到的,代碼工作,但只有一次一個文件。應該是一個相對簡單的修復工作,但我對bash腳本非常陌生,似乎無法解決它。不好意思,不好意思。我做了一些研究來找到答案,但沒有找到我所需要的。預先感謝您的幫助。
編輯 我發現了兩個不同的問題解決方案。作爲@David Z的建議,可以通過刪除腳本的錯誤檢查部分以及在find函數中將$ _files變量加上引號來解決這個問題。然後代碼如下所示:
#!/bin/bash
_files=$1
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
for f in $(find -name "$_files")
做
if [ -s $f ]
then
echo "$f has some data."
# do something as file has data
else
echo "$f is empty. Deleting file."
rm $f
fi
做
或者,你也可以簡單地以 「$ @」,它允許誤差改變for循環對於f檢查是否保存在腳本中。我不確定哪種方法更好,但如果我找到了,會再次更新。
您需要引用命令行參數和'$ _files'處處以防止擴張。 – Mat
難道你不能在一個'find'命令中做這個嗎? – marekful
只要_files_和_recursive_關聯在bash問題中,顯而易見的答案應該是['find'](https://en.wikipedia.org/wiki/Find_(Unix))。 – mouviciel