bash 从 shell 脚本检查目录是否包含文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/91368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking from shell script if a directory contains files
提问by ionn
From a shell script, how do I check if a directory contains files?
从 shell 脚本中,如何检查目录是否包含文件?
Something similar to this
类似的东西
if [ -e /some/dir/* ]; then echo "huzzah"; fi;
but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).
但如果目录包含一个或多个文件(上述文件仅适用于 0 或 1 个文件),则该方法有效。
采纳答案by Bruno De Fraine
The solutions so far use ls
. Here's an all bash solution:
到目前为止的解决方案使用ls
. 这是一个全 bash 解决方案:
#!/bin/bash
shopt -s nullglob dotglob # To include hidden files
files=(/some/dir/*)
if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi
回答by olibre
Three best tricks
三大绝招
shopt -s nullglob dotglob; f=your/dir/*; ((${#f}))
shopt -s nullglob dotglob; f=your/dir/*; ((${#f}))
This trick is 100% bash
and invokes (spawns) a sub-shell. The idea is from Bruno De Fraineand improved by teambob's comment.
这个技巧是 100%bash
并调用(产生)一个子外壳。这个想法来自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
Note:no difference between an empty directory and a non-existing one (and even when the provided path is a file).
注意:空目录和不存在的目录之间没有区别(即使提供的路径是文件)。
There is a similar alternative and more details (and more examples) on the 'official'FAQ for #bash IRC channel:
#bash IRC 频道的“官方”常见问题解答中有类似的替代方法和更多详细信息(以及更多示例):
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)" ]
[ -n "$(ls -A your/dir)" ]
This trick is inspired from nixCraft's articleposted in 2007. Add 2>/dev/null
to suppress the output error "No such file or directory"
.
See also Andrew Taylor's answer (2008) and gr8can8dian's answer (2011).
这个技巧的灵感来自nixCraft在 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
or the one-line bashism version:
或单行 bashism 版本:
[[ $(ls -A your/dir) ]] && echo "contains files" || echo "empty"
Note:ls
returns $?=2
when the directory does not exist. But no difference between a file and an empty directory.
注意:当目录不存在时ls
返回$?=2
。但是文件和空目录之间没有区别。
[ -n "$(find your/dir -prune -empty)" ]
[ -n "$(find your/dir -prune -empty)" ]
This last trick is inspired from gravstar's answerwhere -maxdepth 0
is replaced by -prune
and improved by phils's comment.
这最后绝招是从灵感gravstar的答案在那里-maxdepth 0
被替换-prune
和改进菲尔斯的评论。
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
a variation using -type d
:
使用的变体-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
Explanation:
解释:
find -prune
is similar thanfind -maxdepth 0
using less charactersfind -empty
prints the empty directories and filesfind -type d
prints directories only
find -prune
类似于find -maxdepth 0
使用较少的字符find -empty
打印空目录和文件find -type d
仅打印目录
Note:You could also replace [ -n "$(find your/dir -prune -empty)" ]
by just the shorten version below:
注意:您也可以[ -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
This last code works most of the cases but be aware that malicious paths could express a command...
最后一段代码适用于大多数情况,但请注意恶意路径可以表达命令......
回答by mweerden
How about the following:
以下情况如何:
if find /some/dir/ -maxdepth 0 -empty | read v; then echo "Empty dir"; fi
This way there is no need for generating a complete listing of the contents of the directory. The read
is both to discard the output and make the expression evaluate to true only when something is read (i.e. /some/dir/
is found empty by find
).
这样就不需要生成目录内容的完整列表。该read
既是丢弃输出,使表达时,才读一些评估为真(即/some/dir/
被发现空find
)。
回答by Greg Hewgill
Try:
尝试:
if [ ! -z `ls /some/dir/*` ]; then echo "huzzah"; fi
回答by Gravstar
Take care with directories with a lot of files! It could take a some time to evaluate the ls
command.
小心包含大量文件的目录!评估ls
命令可能需要一些时间。
IMO the best solution is the one that uses
IMO 最好的解决方案是使用
find /some/dir/ -maxdepth 0 -empty
回答by gr8can8dian
# Works on hidden files, directories and regular files
### isEmpty()
# This function takes one parameter:
# is the directory to check
# Echoes "huzzah" if the directory has files
function isEmpty(){
if [ "$(ls -A )" ]; then
echo "huzzah"
else
echo "has no files"
fi
}
回答by Andrew Taylor
DIR="/some/dir"
if [ "$(ls -A $DIR)" ]; then
echo 'There is something alive in here'
fi
回答by DGM
Could you compare the output of this?
你能比较一下这个输出吗?
ls -A /some/dir | wc -l
回答by Roland Illig
# Checks whether a directory contains any nonhidden files. # # usage: if isempty "$HOME"; then echo "Welcome home"; fi # isempty() { for _ief in /*; do if [ -e "$_ief" ]; then return 1 fi done return 0 }
Some implementation notes:
一些实现说明:
- The
for
loop avoids a call to an externalls
process. It still reads all the directory entries once. This can only be optimized away by writing a C program that uses readdir() explicitly. - The
test -e
inside the loop catches the case of an empty directory, in which case the variable_ief
would be assigned the value "somedir/*". Only if that file exists will the function return "nonempty" - This function will work in all POSIX implementations. But be aware that the Solaris /bin/sh doesn't fall into that category. Its
test
implementation doesn't support the-e
flag.
- 该
for
环路避免外部调用ls
过程。它仍然读取所有目录条目一次。这只能通过编写显式使用 readdir() 的 C 程序来优化。 - 在
test -e
循环内捕获了一个空的目录,在此情况下,可变的情况下,_ief
将被指定为值“somedir / *”。仅当该文件存在时,该函数才会返回“非空” - 此函数将适用于所有 POSIX 实现。但请注意,Solaris /bin/sh 不属于该类别。它的
test
实现不支持该-e
标志。
回答by Daishi
This tells me if the directory is empty or if it's not, the number of files it contains.
这告诉我目录是否为空,如果不是,则告诉我它包含的文件数。
directory="/some/dir"
number_of_files=$(ls -A $directory | wc -l)
if [ "$number_of_files" == "0" ]; then
echo "directory $directory is empty"
else
echo "directory $directory contains $number_of_files files"
fi