如何从 shell 脚本检查目录是否包含文件?
类似的东西
if [ -e /some/dir/* ]; then echo "huzzah"; fi;
但如果目录包含一个或多个文件(上面的文件仅适用于恰好 0 或 1 个文件),则该方法有效。
最佳答案
三个最好的技巧
shopt -s nullglob dotglob; f=你的/目录/*; ((${#f}))
这个技巧是 100% bash
并调用(生成)子 shell。思路来自Bruno De Fraine并通过 teambob 进行了改进的评论。
files=$(shopt -s nullglob dotglob; echo your/dir/*)
if (( ${#files} ))
then
echo "contains files"
else
echo "empty (or does not exist or is a file)"
fi
注意:空目录和不存在的目录(即使提供的路径是文件)之间没有区别。
'official' FAQ for #bash IRC channel 上有类似的替代方案和更多详细信息(以及更多示例) :
if (shopt -s nullglob dotglob; f=(*); ((${#f[@]})))
then
echo "contains files"
else
echo "empty (or does not exist, or is a file)"
fi
[ -n "$(ls -A your/dir)"]
这个技巧的灵感来自 nixCraft's article发表于 2007 年。添加 2>/dev/null
以抑制输出错误 “No such file or directory”
。
另见 Andrew Taylor的回答 (2008) 和 gr8can8dian的回答(2011 年)。
if [ -n "$(ls -A your/dir 2>/dev/null)" ]
then
echo "contains files (or is a file)"
else
echo "empty (or does not exist)"
fi
或单行 bashism 版本:
[[ $(ls -A your/dir) ]] && echo "contains files" || echo "empty"
注意: ls
当目录不存在时返回$?=2
。但是文件和空目录没有区别。
[ -n "$(find your/dir -prune -empty)"]
最后一个技巧的灵感来自 gravstar's answer其中 -maxdepth 0
替换为 -prune
并由 phils 改进的评论。
if [ -n "$(find your/dir -prune -empty 2>/dev/null)" ]
then
echo "empty (directory or file)"
else
echo "contains files (or does not exist)"
fi
使用 -type d
的变体:
if [ -n "$(find your/dir -prune -empty -type d 2>/dev/null)" ]
then
echo "empty directory"
else
echo "contains files (or does not exist or is not a directory)"
fi
解释:
find -prune
与find -maxdepth 0
相似,使用更少的字符find -empty
打印空目录和文件find -type d
仅打印目录
注意:您还可以将 [ -n "$(find your/dir -prune -empty)"]
替换为以下缩短版本:
if [ `find your/dir -prune -empty 2>/dev/null` ]
then
echo "empty (directory or file)"
else
echo "contains files (or does not exist)"
fi
最后一段代码适用于大多数情况,但请注意恶意路径可能会表达命令...
关于bash - 从 shell 脚本检查目录是否包含文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/91368/