Bash参数扩展仅在交互式Shell中有效,而在脚本中无效 [英] Bash parameter expansion works only in interactive shell, but not in script

查看:70
本文介绍了Bash参数扩展仅在交互式Shell中有效,而在脚本中无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在用户控制台中,我有bash:

In user's console I have bash:

$ echo $SHELL
/bin/bash
$ bash --version
GNU bash, version 4.2.46(1)-release (x86_64-redhat-linux-gnu)

我在文件test.sh中有代码:

I have code in file test.sh:

$ cat test.sh
aaa='---aa-aa---'
echo "${aaa}"
echo 'does not work...'
# trim "-"
echo ${aaa/+(-)}
echo ${aaa%%+(-)}
echo 'works for one symbol...'
echo ${aaa%-}
echo ${aaa/-}

最后两行可以正常工作,但以前的行可以.

The last two rows work fine but previous ones.

$ bash test.sh
---aa-aa---
does not work...
---aa-aa---
---aa-aa---
works for one symbol...
---aa-aa--
--aa-aa---

同时,如果您尝试制作此控制台,它将起作用:

In the same time, if you would try to make this console it works:

$ aaa='---aa-aa---'
$ echo ${aaa/+(-)}
aa-aa---
$ echo ${aaa%%+(-)}
---aa-aa

那么,为什么它在脚本中不起作用?

So, why it doesn't work in a script?

推荐答案

您似乎已在交互式外壳程序中启用了shopt -s extglob,从而打开了扩展的globing.这不是默认行为,需要在脚本中显式启用.有关详细信息,请参见bash黑客Wiki中的扩展模式匹配.

You seem to have shopt -s extglob enabled in your interactive shell, which turns on extended globbing. This is not the default behavior, and needs to be explicitly enabled in your script. See extended pattern matching in the bash hackers wiki for details.

这篇关于Bash参数扩展仅在交互式Shell中有效,而在脚本中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆