[英]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 这是我的“ WTF”时刻
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. 我知道那里有一个
bash
专家可以解释这一点,我将不胜感激知道发生了什么。
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. 如果具有元字符(
*
, [...]
等)的glob不匹配文件名,则该glob不变地返回。
echo "role[sugar]"
echo "role[blerk]"
The default behaviour of the shell is to expand a glob where possible, otherwise return it unchanged. Shell的默认行为是在可能的情况下扩展glob,否则将其保持不变。 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
: 要将不匹配的glob扩展为空字符串(例如,对于
for
循环很有用,例如,如果没有文件匹配,您可能只想跳过该循环),请使用nullglob
:
shopt -s nullglob
If the fact that the glob doesn't expand is considered an error, use failglob
: 如果将glob无法扩展这一事实视为错误,请使用
failglob
:
shopt -s failglob
Use shopt -u
to unset these shell options. 使用
shopt -u
取消设置这些shell选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.