简体   繁体   中英

bash shell gives weird result when directory exists vs not

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.

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]"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM