为什么bash“echo [t]”导致“t”而不是“[t]”

前端之家收集整理的这篇文章主要介绍了为什么bash“echo [t]”导致“t”而不是“[t]”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这发生在字符t和值根。相当困惑
  1. $ echo [s]
  2. [s]
  3. $ echo [t]
  4. t
  5. $ echo [ t ]
  6. [ t ]
  7. $ echo [root]
  8. t
不是一个壳的习惯(并不愿意成为)我发现令人惊讶的如何文件名扩展被设计为行为时,没有找到匹配。我会报 Bash reference

Bash scans each word for the characters *,?,and [. If one of
these characters appears,then the word is regarded as a pattern,and
replaced with an alphabetically sorted list of file names matching the
pattern. If no matching file names are found:

  • if the shell option nullglob is disabled,the word is left unchanged
  • if the shell option nullglob is set the word is removed
  • If the failglob shell option is set,an error message is printed and the command is not executed

好消息是这件事是可配置的。坏的一个是一个脚本可以失败在许多方式,一个人不期望 – 至少,我没有,我花了一些时间来了解为什么echo行为的方式,你发布,只是发现,这是因为一个组合的古怪的文件名(谁想要命名文件t?),隐藏配置(nullglob禁用,默认选项但仍隐藏)和一个无害的命令。

我说无害,因为这是你得到的,例如,当目标是ls(失败,因为没有找到文件):

  1. raffaele@Aldebaran:~$ mkdir test
  2. raffaele@Aldebaran:~$ cd test
  3. raffaele@Aldebaran:~/test$ touch t
  4. raffaele@Aldebaran:~/test$ ls [t]
  5. t
  6. raffaele@Aldebaran:~/test$ ls [v]
  7. ls: cannot access [v]: No such file or directory

猜你在找的Bash相关文章