help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] The best way to test whether a directory has *.txt files


From: Greg Wooledge
Subject: Re: [Help-bash] The best way to test whether a directory has *.txt files?
Date: Thu, 28 Jun 2012 08:00:49 -0400
User-agent: Mutt/1.4.2.3i

On Thu, Jun 28, 2012 at 04:44:49PM +0800, Clark WANG wrote:
> > There can be more than one way to test whether a directory contains
> > *.txt files (to be used with 'find -exec'). But I'm wondering what is
> > the best way (in terms of convenience to type) to do it.

There is no "best way".  There are ways that don't work, and there are
ways that STILL don't work, and then, every once in a great while, you
may find a way that actually does work.

For example, any trick that expands a glob and then compares the result
to the literal glob is wrong, because the glob itself is also a valid
filename.

# Wrong.
touch '*'
if [[ `echo *` = '*' ]]; then echo "Derp, I think there are no files"; fi
# Wrong.

> > Does anybody have any tricks on this?

http://mywiki.wooledge.org/BashFAQ/004

> I've ever seen this:
> 
> ( shopt -s nullglob; set -- /the/dir/*.txt; (( $# )) )

I'm not fond of subshells for this kind of task, due to the performance
penalties.  Personally I'd just use:

shopt -s nullglob dotglob
files=(/the/dir/*.txt); address@hidden
shopt -u nullglob dotglob

This also has the advantage of leaving an array populated with the
filenames for later iteration or whatever.  With the subshell approach,
that array is discarded.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]