BASH and wildcard expansion

Suvayu Ali fatkasuvayu+linux at gmail.com
Tue Aug 20 07:29:51 UTC 2013


Hi Bill,

On Mon, Aug 19, 2013 at 07:56:03PM -0500, Bill Oliver wrote:
> On Tue, 20 Aug 2013, Suvayu Ali wrote:
> 
> >On Mon, Aug 19, 2013 at 05:18:40PM -0500, Bill Oliver wrote:
> >>
> >># Filename format YYYY_MM_DD--HHMM.zip
> >>filename="$log_year-$log_month-$log_day--*.zip"
> >>
> >>filelist=`ls $filename`
> >
> >Please don't do this.  A much better solution is:
> >
> >filelist=($log_year-$log_month-$log_day--*.zip)
> >
> >See: <http://mywiki.wooledge.org/ParsingLs>
> >

 [...chomp...chomp...chomp...]

> 
> # Filename format YYYY_MM_DD--HHMM.zip
> filelist=($log_year-$log_month-$log_day--*.zip)
> 
> 
> ******************
> 
> I get:
> 
> $ ./jnk2.sh
> 2013-August-19--a.zip
> 
> For some reason, the second file (013-August-19--ba.zip) is not returned...

My fault, I should have been more verbose.

The var=(..) creates an array variable; whereas the var=$(..) construct
runs a sub-shell and stores the output as a string (the last one is
equivalent to var=`..`).

So with my example you can get your list back by using the array.

  $ echo ${filelist[@]}

Putting files in an array also lets you loop over them easily.

  for file in ${filelist[@]};
  do
     some_cmd;
  done

(or in oneline: for file in ${filelist[@]}; do some_cmd; done)

As you can see to access the whole array, I use the [@] index.  You can
also use [*] there.  There is a subtle difference between the two when
in side double quotes, otherwise they are equivalent.  You can read all
about it in the bash info page under array (info "(bash) Arrays").

To access individual files in the array you can use: ${filelist[1]}

That said, I do not think storing the files in a variable is necessary
at all.  This is how I would do it.

  for file in $log_year-$log_month-$log_day--*.zip;
  do
     some_cmd;
  done

Simple and easy!

Hope this helps,

-- 
Suvayu

Open source is the future. It sets us free.


More information about the users mailing list