模式在交互式shell中有效,但在脚本中无效
在我的交互式 shell 中,我可以将模式存储在变量中
$ targets="?(pcm52|pcm61)"
$ ls -l config/devdesc.$targets
-rw-r--r-- 1 kfa kfa 113 Dec 16 13:43 config/devdesc.pcm52
-rw-r--r-- 1 kfa kfa 14 Dec 16 13:44 config/devdesc.pcm61
但是如果我创建一个shell脚本
targets="?(pcm52|pcm61)"
ls -l config/devdesc.$targets
运行它时出现此错误
$ bash -x /tmp/e.sh
+ targets='?(pcm52|pcm61)'
+ ls -l 'config/devdesc.?(pcm52|pcm61)'
ls: cannot access 'config/devdesc.?(pcm52|pcm61)': No such file or directory
为什么放入脚本时会失败?
回答
从 Bash 手册页:
如果
extglob使用shopt内置函数启用了shell 选项,则会识别多个扩展模式匹配运算符。
因此,只需将脚本添加shopt -s extglob到开头e.sh,因为它不会从交互式会话中继承该非默认选项。
- So specifically to "Why does it fail when put into a script?": because you are using an extended glob pattern, support for those depends on a non-default shell option, and that option is not inherited by your script.