我想知道,如果我的解决方案找到一个文件名或"文件类型">与if语句结合使用是好的做法吗?也许有一种更安全/更好的方法来做这样的事情?
#!/usr/bin/env bash
DIR="/home/user"
SUB_DIR="/Downloads"
if [[ -n "$(find $DIR$SUB_DIR -depth -type f -name '*.jpg' -print0 -quit 2>/dev/null)" ]]; then
echo "Found JPG-File"
elif [[ -n "$(find $DIR$SUB_DIR -depth -type f -name '*.png' -print0 -quit 2>/dev/null)" ]]; then
echo "Found PNG-File"
#... and much more elif statements
fi
-print0
-如果文件名中有空格
-quit
-第一个捕获并退出查找命令
我还使用这行代码从搜索中排除子文件夹:
if [[ -n "$(find $DIR$SUB_DIR -type d ( -path */RAW* -o -path */VIDEO* ) -prune -o -type f -name '*.jpg' -print0 -quit 2>/dev/null)" ]]; then
echo "Some other stuff"
fi
是好的做法吗?
$DIR$SUB_DIR
未被引用,因此会进行分词和文件名扩展。使用shellcheck.net检查您的脚本以发现此类错误。
不要禁用错误-2>/dev/null
-它们可能会向用户提供失败的各种提示-权限被拒绝,目录不存在,等等。
局部变量不要使用大写的变量。更喜欢使用小写可变大小写。
也许有一种更安全/更好的方法来做这样的事情?
检查find
退出状态。
移除-depth
。为什么要使用它?
打印一个点,而不是打印整个文件名。或者什么都可以。它将比文件名更短,因此将使用更少的内存。
if tmp="$(find "$dir/$sub_dir" ... -print . -quit)" && [[ -n "$tmp" ]]; then
另请参阅测试glob在bash中是否有匹配项。