我正在嘗試在腳本中使用非常基本的 Bash 引數擴展,但它不起作用;不過,當我在互動式 shell 中運行它時,它運行良好。這是小測驗腳本:
<~> $ cat /tmp/foo
#!/usr/bin/env bash
foo="bar 1.2.3"
echo $foo
echo ${foo##*([^0-9])}
echo ${foo/a/-}
當我運行腳本時,第一個引數擴展 ( ${foo##*([^0-9])}) 不起作用,但第二個 ( ${foo/a/-}) 起作用:
<~> $ /tmp/foo
bar 1.2.3
bar 1.2.3
b-r 1.2.3
如果我改為獲取它(在我當前的 shell 中運行它),它會按預期作業:
<~> $ . /tmp/foo
bar 1.2.3
1.2.3
b-r 1.2.3
懷疑正在運行的實際 shell、shell 版本或設定存在差異,我擴展了腳本:
<~> $ cat /tmp/foo
#!/usr/bin/env bash
echo "SHELL: $SHELL"
echo "VERSION: $BASH_VERSION"
echo
set -o
echo
foo="bar 1.2.3"
echo $foo
echo ${foo##*([^0-9])}
echo ${foo/a/-}
現在我明白了:
<~> $ /tmp/foo
SHELL: /opt/local/bin/bash
VERSION: 5.1.16(1)-release
allexport off
braceexpand on
emacs off
errexit off
errtrace off
functrace off
hashall on
histexpand off
history off
ignoreeof off
interactive-comments on
keyword off
monitor off
noclobber off
noexec off
noglob off
nolog off
notify off
nounset off
onecmd off
physical off
pipefail off
posix off
privileged off
verbose off
vi off
xtrace off
bar 1.2.3
bar 1.2.3
b-r 1.2.3
沒有什么不合適的,運行兩者并比較輸出沒有任何意義:
<~> $ diff <(/tmp/foo) <(. /tmp/foo)
6c6
< emacs off
---
> emacs on
11,12c11,12
< histexpand off
< history off
---
> histexpand on
> history on
16c16
< monitor off
---
> monitor on
33c33
< bar 1.2.3
---
> 1.2.3
關于我在這里缺少什么的任何想法(除了一個線索,'natch)?謝謝!
附錄
只是為了繪制從下面接受的答案派生的完整圖片,添加shopt到腳本輸出中顯示了腳本版本和互動式 shell 版本之間的這些額外差異:
52c52
< expand_aliases off
---
> expand_aliases on
54c54
< extglob off
---
> extglob on
61c61
< histappend off
---
> histappend on
64c64
< hostcomplete on
---
> hostcomplete off
72c72
< login_shell off
---
> login_shell on
確實缺少選項 ( extglob)。
uj5u.com熱心網友回復:
您需要添加
shopt -s extglob
到腳本以啟用*(pattern-list)擴展通配符。我懷疑您在.bashrc.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/453366.html
下一篇:在bash中轉義字符
