bash shell gives weird result when directory exist

2020-04-21 04:46发布

问题:

Alright, I've wasted a full day on a script that was behaving very oddly. I have found out something that I can't explain.

ny-02-ops:~$ rm -fr roles
ny-02-ops:~$ echo role[blerk]
role[blerk]
ny-02-ops:~$ echo role[sugar]
role[sugar]
ny-02-ops:~$ mkdir roles
ny-02-ops:~$ echo role[blerk]
role[blerk]

Here's my "WTF" moment

ny-02-ops:~$ echo role[sugar]
roles
ny-02-ops:~$ mkdir roleb
ny-02-ops:~$ echo role[blerk]
roleb

I know there's a bash guru out there who can explain this, and I would be very grateful to know what's going on.

回答1:

Square brackets in a glob match one of the characters inside. If a glob with metacharacters (*, [...], etc.) matches no filenames then the glob is returned unchanged.

echo "role[sugar]"
echo "role[blerk]"


回答2:

The default behaviour of the shell is to expand a glob where possible, otherwise return it unchanged. There are ways to change this behaviour, however.

To expand non-matching globs to an empty string (useful for for loops which you may just want to skip if no files match, for example), use nullglob:

shopt -s nullglob

If the fact that the glob doesn't expand is considered an error, use failglob:

shopt -s failglob

Use shopt -u to unset these shell options.



标签: linux bash shell