简体   繁体   中英

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

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. They are marked by ## Begin file test here and ## 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:

EDIT I missed that you were looking for > 2 files. 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. Alternatively use find , since it does that by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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