我有以下 BASH 脚本:http://pastebin.com/CX4RN1QW
脚本中有两个部分,仅当目录中的文件数为 2 或更大时,我才想运行。它们以## Begin file test here
和## End file test.
标记
我对脚本非常敏感,我不希望其他任何更改,即使它简化了它。
我试过:
if [ "$(ls -b | wc -l)" -gt 1 ];
但这没有用。
您可以使用 glob 检查目录中是否存在文件,而不是使用外部 ls
命令:
编辑 我错过了您正在寻找> 2 个文件。更新。
shopt -s nullglob # cause unmatched globs to return empty, rather than the glob itself
files=(*) # put all file in the current directory into an array
if (( "${#files[@]}" >= 2 )); then # since we only care about existence, we only need to expand the first element
...
fi
shopt -u nullglob # disable null glob (not required)
你需要
ls -1
才能工作,因为 -b 不会让它每行打印一个项目。或者使用 find
,因为它默认这样做。