bash脚本在获取时会产生不同的结果 [英] bash script yields a different result when sourced
问题描述
您能帮我吗,为什么这个脚本在来源(甚至直接在控制台上)时起作用而在脚本上不起作用?
Could you help me, why this script works when sourced (or even directly on console) and does not work on a script?
我已经检查过了,无论如何我都在/bin/中使用相同的bash,并且始终使用4.4.19(1)-release(已通过$BASH_VERSION
检查).
I have checked and in any case I'm using the same bash in /bin/ and always 4.4.19(1)-release (checked with $BASH_VERSION
).
此外,我尝试删除了shebang,但没有任何变化.
Moreover I tried removing shebang but nothing changes.
#!/bin/bash
fname=c8_m81l_55.fit
bname=${fname%%+(_)+([0-9]).fit}
echo $bname
给出以下结果:
test:~$ ./test.sh
c8_m81l_55.fit
test:~$ . ./test.sh
c8_m81l
推荐答案
除非启用了extglob,并且默认情况下将其禁用,否则Bash无法识别+(pattern)
语法.显然,您的bash设置可以在交互式会话中启用它们;这就是为什么您的脚本仅在来自交互式shell的情况下才能工作.
Bash does not recognize +(pattern)
syntax unless extglobs are enabled, and they are disabled by default. Apparently your bash setup enables them in interactive sessions; that's why your script works only when sourced in an interactive shell.
要解决此问题,请通过以下命令在脚本中启用extglob:
To fix that, either enable extglobs within the script by this command:
shopt -s extglob
或使用不管外壳的交互性如何都有效的替代方法:
Or use an alternative that works irrespective of shell's interactiveness:
bname=$(sed 's/__*[0-9][0-9]*\.fit$//' <<< $fname)
# with GNU sed it'd look like:
bname=$(sed -E 's/_+[0-9]+\.fit$//' <<< $fname)
这篇关于bash脚本在获取时会产生不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!