[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: List expansion in a 'for in' control structure
From: |
Bob Proulx |
Subject: |
Re: List expansion in a 'for in' control structure |
Date: |
Sat, 30 Jul 2005 10:01:46 -0600 |
User-agent: |
Mutt/1.5.9i |
Till Halbach wrote:
> Bash Version: 2.05b
> The bash manual for the control structure 'for name [ in word ] ; do list
> ; done' says:
> 'The list of words following in is expanded, generating a list of
> items.' However, if no files are found, it is set equal to the query
> string.
Yes. That is correct.
You are apparently mixing two behaviors together. This really has
nothing to do with the for loop. The for loop is simply looping
through its arguments. This really has to to do with how the shell
does pathname expansion which is part of the bigger problem of command
line expansion. In your case above don't think about the for loop,
think about just the filename expansion. For example you can use
"echo" to reduce this to a simpler problem.
echo GLOB
> Assume you have a directory with some files beginning with 'a' and none
> beginning with 'z'.
> >for file in a*.html; do echo $file; done
> abbr.html
> acronym.html
> address.html
> a.html
> applet.html
Yes. The glob pattern matched the files in the directory. They are
expanded. The for loop is passed the result of the expansion. You can
also repeat this simply with echo.
echo a*.html
The for loop is then looping through all of the arguments provided to
it.
> >for file in z*.html; do echo $file; done
> z*.html
Yes. You can repeat this simply with echo.
echo z*.html
The for loop is then looping through all of the arguments provided to
it. You are reporting this as if you think this must be a bug. But
this is the correct behavior for a shell to have in this case.
> If no files are found, the list of words (represented by word in the
> command description above) should expand to a zero-element array, but not
> to the word itself.
No. That would not match the expected shell behavior. The expected
shell behavior is that if the file glob pattern is not expanded by the
shell then the string itself will remain verbatim.
You can get the behavior you are asking for by setting the "nullglob"
shell option.
shopt -s nullglob
The bash manual has this documentation:
nullglob
If set, bash allows patterns which match no
files (see Pathname Expansion above) to expand
to a null string, rather than themselves.
Please see the Pathname Expansion section of the bash manual for more
information.
Bob