如何使用bash测试目录中文件的存在
if ... ; then
echo 'Found some!'
fi为了明确起见,我不想测试是否存在特定的文件。我想测试一个特定的目录是否包含任何文件。
我跟着:
(
shopt -s dotglob nullglob
existing_files=( ./* )
if [[ ${#existing_files[@]} -gt 0 ]] ; then
some_command "${existing_files[@]}"
fi
)使用该数组可避免两次读取文件列表的竞争条件。
发布于 2012-01-19 05:33:12
我通常只使用一个廉价的ls -A来查看是否有响应。
伪-也许-正确-语法-示例-ahoy:
if [[ $(ls -A my_directory_path_variable ) ]] then....编辑,这将工作:
myDir=(./*) if [ ${#myDir[@]} -gt 1 ]; then echo "there's something down here"; fi
发布于 2012-01-19 05:30:40
从手册页:
-f file
True if file exists and is a regular file.所以:
if [ -f someFileName ]; then echo 'Found some!'; fi编辑:我看到你已经得到了答案,但是为了完整,你可以使用Checking from shell script if a directory contains files中的信息-如果你想要忽略隐藏的文件,就会失去dotglob选项。
发布于 2012-01-19 05:39:51
因此,可以在ls语句中使用if:
if [[ "$(ls -a1 | egrep -v '^\.$|^\.\.$')" = "" ]] ; then echo empty ; fi或者,多亏了池伽米
if [[ "$(ls -A)" = "" ]] ; then echo empty ; fi或者,甚至更短:
if [[ -z "$(ls -A)" ]] ; then echo empty ; fi这些文件基本上列出了当前目录中既不是.也不是..的所有文件(包括隐藏的文件)。
如果该列表为空,则该目录为空。
如果要对隐藏文件进行折扣,可以将其简化为:
if [[ "$(ls)" = "" ]] ; then echo empty ; fibash-only解决方案(不调用ls或egrep之类的外部程序)可以执行以下操作:
emp=Y; for i in *; do if [[ $i != "*" ]]; then emp=N; break; fi; done; echo $emp它不是世界上最漂亮的代码,它只是将emp设置为Y,然后,对于每个真正的文件,将其设置为N,并从for循环中分离出来以提高效率。如果有零个文件,它将保留为Y。
https://stackoverflow.com/questions/8921441
复制相似问题