[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: what is wrong here?
From: |
Greg Wooledge |
Subject: |
Re: what is wrong here? |
Date: |
Wed, 28 Mar 2012 14:42:11 -0400 |
User-agent: |
Mutt/1.4.2.3i |
On Mon, Aug 08, 2011 at 03:41:52PM +0200, mhenn wrote:
> Am 08.08.2011 15:22, schrieb Francky Leyn:
> > On 8/8/2011 2:17 PM, mhenn wrote:
> >> Am 08.08.2011 11:33, schrieb Francky Leyn:
> >>> consider the following code:
> >>>
> >>> EXTENSION=jpg
> >>> INPUT_FILES=*.$EXTENSION
> >>
> >> echo "$INPUT_FILES" #obviously wrong
> >> #instead maybe
> >> INPUT_FILES="$(ls *.$EXTENSION)"
They are both incorrect. If you want a list of all the files that match
a glob, use an array to hold them:
files=(*.$extension)
Parameter expansion ($extension) happens before globbing (*.jpg), and
the results will be placed into an array. Filenames with whitespace
will be handled correctly.
> > This worked when there were files.
> > But when there were no matching files, it didn't.
If you want the array to be empty when there are no matching files, then
you must enable bash's nullglob option:
shopt -s nullglob
files=(*.$extension)
See also http://mywiki.wooledge.org/BashFAQ/004 (checking/counting files)
and http://mywiki.wooledge.org/BashFAQ/005 (arrays)
and http://mywiki.wooledge.org/glob (globs)
Using ls in a script is almost always wrong, unless you're simply dumping
its output to a terminal for a human to read. Use globs instead.