如何使用bash?测试目录中文件的存在?
if ... ; then
echo 'Found some!'
fi
Run Code Online (Sandbox Code Playgroud)
要清楚,我不想测试特定文件的存在.我想测试一个特定的目录是否包含任何文件.
我去了:
(
shopt -s dotglob nullglob
existing_files=( ./* )
if [[ ${#existing_files[@]} -gt 0 ]] ; then
some_command "${existing_files[@]}"
fi
)
Run Code Online (Sandbox Code Playgroud)
使用该数组可以避免竞争条件两次读取文件列表.
Con*_*ltz 12
从手册页:
-f file
True if file exists and is a regular file.
Run Code Online (Sandbox Code Playgroud)
所以:
if [ -f someFileName ]; then echo 'Found some!'; fi
Run Code Online (Sandbox Code Playgroud)
编辑:我看到你已经得到了答案,但为了完整,你可以使用在shell脚本中检查信息,如果目录包含文件 - 如果你想隐藏隐藏文件,则丢失dotglob选项.
小智 7
我通常只使用便宜的ls -A来查看是否有响应.
伪也许,正确的语法,例如,趣多多:
if [[ $(ls -A my_directory_path_variable ) ]] then....
Run Code Online (Sandbox Code Playgroud)
编辑,这将工作:
myDir=(./*) if [ ${#myDir[@]} -gt 1 ]; then echo "there's something down here"; fi