【发布时间】:2012-01-19 05:26:28
【问题描述】:
如何使用bash 测试目录中是否存在文件?
if ... ; then
echo 'Found some!'
fi
明确地说,我不想测试 特定 文件是否存在。我想测试一个特定目录是否包含 any 个文件。
我去了:
(
shopt -s dotglob nullglob
existing_files=( ./* )
if [[ ${#existing_files[@]} -gt 0 ]] ; then
some_command "${existing_files[@]}"
fi
)
使用数组避免了两次读取文件列表的竞争条件。
【问题讨论】:
-
目录包含子目录但没有普通文件怎么办?
-
@Keith Thompson,不会发生。
-
如果目录比较大,做一个 glob 是个坏主意。 ls -f 会快得多。
-
@William Pursell,如何从
ls加载数组?