2017-02-09 115 views
0

前安全检查我有一个脚本,它确实需要在一个特定的文件夹

我想使这个尽可能安全的RM -fr。我在下面开始了这个脚本,但我想知道是否还有其他东西我错过了。

folder="" 

if [[ ! -d "$folder" ]]; then 
    echo "Error: is not a folder" 
elif [[ "$folder" == "/" ]]; then 
    echo "Error: folder points to root" 
elif [[ "$folder" == "../"* ]]; then 
    echo "Error: folder start with ../" 
elif [[ "$folder" == *"/.."* ]]; then 
    echo "Error: folder contains /.." 
elif [[ "$folder" == *"/*"* ]]; then 
    echo "Error: folder ends with /*" 
else 
    rm -fr "$folder" 
fi 

更新:添加了检查“/”

+2

也可能检查'/'? – codeforester

+0

谢谢我更新了代码! – Zurd

+0

是位于给定用户下的所有文件夹..例如〜/ home/jsmith? – zee

回答

0

如果你想尽可能安全,你也许可以......

确保任何通配首先完成:

shopt -s nullglob 
declare -a folders=(folder_or_glob) 

迭代数组中的每个元素,一次一个,并在规范路径上运行。

for f in "${folders[@]-}" 
do 
    [[ $f ]] || continue 
    candidate="$(realpath -e -s "$f")" || continue 
    ok_to_delete "$candidate" || continue 
    rm -rf "$candidate" 
done 

使用功能ok_to_delete测试:

ok_to_delete() 
{ 
    [[ -d $1 ]] || continue  # Is directory 
    [[ $1 !=/]] || continue # Not root 
    [[ "${1%/*}" ]] || continue # At least two levels deep 
    (... add any test you want ...) 
} 

有一点冗余这里(例如没有根+ 2级深),但是这仅仅是给你的想法。

0

而不是检查文件夹的路径名,我宁愿检查该文件夹中的内容,文件的大小/用户/时间戳/ keywork /扩展等,或任何你最关心的。这对你来说更安全一些,这只是我的两分钱。