除了基本的*
, ?
and [...]
模式,Bash shell 提供了扩展的模式匹配运算符,例如!(pattern-list)
(“匹配除给定模式之一之外的所有模式”)。这extglob
需要设置 shell 选项才能使用它们。一个例子:
~$ mkdir test ; cd test ; touch file1 file2 file3
~/test$ echo *
file1 file2 file3
~/test$ shopt -s extglob # make sure extglob is set
~/test$ echo !(file2)
file1 file3
如果我将 shell 表达式传递给在子 shell 中执行它的程序,则该运算符会导致错误。这是一个直接运行子 shell 的测试(这里我从另一个目录执行以确保扩展不会过早发生):
~/test$ cd ..
~$ bash -c "cd test ; echo *"
file1 file2 file3
~$ bash -c "cd test ; echo !(file2)" # expected output: file1 file3
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `cd test ; echo !(file2)'
我尝试过各种转义,但我想出的方法都没有正确工作。我也怀疑extglob
没有在子 shell 中设置,但情况并非如此:
~$ bash -c "shopt -s extglob ; cd test ; echo !(file2)"
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `cd test ; echo !(file2)'
任何解决方案表示赞赏!
bash 在执行之前会解析每一行,因此当 bash 验证通配模式语法时,“shopt -s extglob”不会生效。无法在同一行上启用该选项。这就是为什么“bash -O extglob -c 'xyz'”解决方案(来自 Randy Proctor)有效并且是必需的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)