2017-10-08 82 views
2

我正在處理這個應該刪除特定擴展名的文件的bash腳本,我不希望它返回一個沒有這樣的文件或目錄輸出,當我檢查這些文件是否仍然存在。相反,我希望它返回一個自定義消息,如:「您已經刪除了這些文件」。 這裏是腳本:Bash腳本刪除一個特定的文件

#!/usr/bin/env bash 
read -p "are you sure you want to delete the files? Y/N " -n 1 -r 
echo 
if [[ $REPLY =~ ^[Yy]$ ]] 
then 
    rm *.torrent 
    rm *.zip 
    rm *.deb 
echo "all those files have been deleted............." 
fi 
+0

你知道'find'命令嗎? –

+0

沒有。我還是新手bash – mots

+1

類似於'find -name'* .torrent'-o -name'* .zip'-o -name'* .deb'-delete'會完全繞過你的問題,但可能不會你想要什麼,因爲它沒有報告什麼時候沒有給定類型的文件開始。 –

回答

0

有提供給你幾個比較優雅的選擇。

一個將rm包裝在一個函數中,該函數檢查是否有任何要刪除文件夾中的文件。你可以使用ls,以檢查是否有符合通配符的任何文件,按照this question

#!/usr/bin/env bash 

rm_check() { 
    if ls *."${1}" 1> /dev/null 2>&1; then 
     rm *."${1}" 
     echo "All *.${1} files have been deleted" 
    else 
     echo "No *.${1} files were found" 
    fi 
} 

read -p "are you sure you want to delete the files? Y/N " -n 1 -r 
echo 
if [[ $REPLY =~ ^[Yy]$ ]]; then 
    rm_check torrent 
    rm_check zip 
    rm_check deb 
fi 

這個版本是不錯的,因爲它擁有一切奠定了最初計劃的方式。

在我看來,一個更清潔的版本只能查看與您的模式相匹配的文件。正如我在評論中建議,你可以用一個單一的find命令做到這一點:

#!/usr/bin/env bash 
read -p "are you sure you want to delete the files? Y/N " -n 1 -r 
echo 
if [[ $REPLY =~ ^[Yy]$ ]]; then 
    find -name '*.torrent' -o -name '*.zip' -o -name '*.deb' -delete 
    echo "all those files have been deleted............." 
fi 

這種方法使你的腳本很短。這種方法唯一可能的缺點是它不會報告缺少哪些文件類型。

1

你可以這樣做:

rm *.torrent *.zip *.deb 2>/dev/null \ 
&& echo "all those files have been deleted............." \ 
|| echo "you have already removed the files" 

這將在存在的所有文件按預期方式工作, 當他們都不存在。

你沒有提到如果他們中的一些存在但不是全部該怎麼辦。 例如,有一些.torrent文件,但沒有.zip文件。

添加第三個情況, 其中只有一些文件都在那裏(現在刪除), 你需要檢查取消對每個文件類型, 的退出代碼和生成基於該報告。

這裏有一個辦法做到這一點:

rm *.torrent 2>/dev/null && t=0 || t=1 
rm *.zip 2>/dev/null && z=0 || z=1 
rm *.deb 2>/dev/null && d=0 || d=1 

case $t$z$d in 
    000) 
    echo "all those files have been deleted............." ;; 
    111) 
    echo "you have already removed the files" ;; 
    *) 
    echo "you have already removed some of the files, and now all are removed" ;; 
esac