简体   繁体   English

BASH:如果目录中的文件数大于或等于2,则需要运行if语句

[英]BASH: If statement needed to run if number of files in directory is 2 or greater

I have the following BASH script: http://pastebin.com/CX4RN1QW 我有以下BASH脚本: http : //pastebin.com/CX4RN1QW

There are two sections within the script that I want to run only if the number of files in the directory are 2 or greater. 仅当目录中的文件数为2或更大时,我才希望运行脚本中的两个部分。 They are marked by ## Begin file test here and ## End file test. 它们在## Begin file test here标记为## Begin file test here## End file test.

I am very sensitive about the script, I don't want anything else to change, even if it simplifies it. 我对脚本非常敏感,我不希望更改任何其他内容,即使它可以简化它。

I have tried: 我努力了:

if [ "$(ls -b | wc -l)" -gt 1 ];

But that didn't work. 但这没有用。

Instead of using the external ls command, you can use a glob to check for the existence of files in a directory: 您可以使用glob来检查目录中是否存在文件,而不是使用外部ls命令:

EDIT I missed that you were looking for > 2 files. 编辑我想念您正在寻找> 2个文件。 Updated. 更新。

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)

You would need ls -1 there for it to work, since -b doesn't make it print one item per line. 您需要在其中使用ls -1才能使其工作,因为-b不会使它每行打印一项。 Alternatively use find , since it does that by default. 或者使用find ,因为默认情况下会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM