Filename brace expansion in scripts

Markus Schönhaber ubuntu-users at list-post.mks-mail.de
Thu Nov 18 18:25:16 UTC 2010


18.11.2010 16:48, Colin Law:

> I have a problem with filename expansion in a script and am having
> difficulty understanding what is going on.
> In a terminal, if I enter
> ls {a*,b*}
> I see all files beginning with a or b (I know this is not the best way
> of doing that but it is a simple example of the problem I am seeing).

Your login shell (i. e. /bin/bash unless you manually changed that)
executes the command and does the file-name globbing beforehand.

> If I put that line in a file test.sh, make it executable, and then type
> ./test.sh
> then I see the same result.

Because it's bash again.

>  However if at the start of test.sh I put the line
> #!/usr/bin/env sh
> at the start of test.sh and then run it I get
> ls: cannot access {f*,l*}: No such file or directory

Now the script is effectively executed by /bin/sh, which, since Hardy
(IIRC), is not a symlink to /bin/bash anymore but to /bin/dash. And dash
doesn't understand most bashisms. That's why it doesn't behave the way
you expected.

> It seems that brace expansion is not being performed in this case.  If
> I just use wildcards it is ok, it is the braces that cause the
> problem.  In order to determine whether a different shell was running
> for some reason I also put
> finger -l
> in the script, and in both cases, with and without the shebang line,
> it showed /bin/bash as the shell.

Which is to be expected. finger -l prints, among other stuff, what is
configured to be the user's login shell. It doesn't tell you anything
about the process that started it.

> If, however, I put
> #!/bin/bash
> at the start then it works, still showing /bin/bash as the shell.

Now again, the script will be run by bash, which, unlike dash, treats
{f*,l*} as a glob and replaces it with a list of matching file-names
before calling ls.

-- 
Regards
  mks




More information about the ubuntu-users mailing list