Re: shell game
Travis Crump <email@example.com> writes:
> Drew Cohan wrote:
>> Using a bash shell script (/bin/sh), I need to know how to check to see
>> if certain files exist in a directory, as in, "Are there any jpegs in
>> this directory?". I've tried various things (like using -s, -f with
>> test and a do/for loop) but nothing seems to work right. The closest I
>> can come is
>> if test `ls /opt/images/*.jpg | wc -l` -gt 0 then ...
>> Unfortunately, this gives me the error message "ls: /opt/images/*.jpg:
>> No such file or directory" when there are no jpegs in /opt/images.
>> So what am I missing here?
> From the there has got to be a better way department:
> ls /opt/images/*.jpg > /dev/null 2>&1 && echo there are jpegs
Here's one of several ways to do it in bash that won't involve forking a
subprocess, in case you want to conserve system resources:
shopt -s nullglob
result=; for result in /opt/images/*.jpg; do break; done
After this, the '$result' variable will be empty unless there are one or
more files which match the pattern.