在某些脚本中,我想使用当前文件夹中的文件夹名称。我想获取文件夹名称,这里我只会把有问题的部分放在例子中。如果我从终端运行它,我会得到:
$ for D in */; do echo ${D%%+(/)} ; done
galaxya8
iphone6s
motog6
motog7
$ echo ${0}
/bin/bash
$ bash --version
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
但是,如果我将其放入一个文件并运行该文件,我会得到带有尾部斜杠的名称:
$ echo 'for D in */; do echo ${D%%+(/)} ; done' >> test.sh
$ bash test.sh
galaxya8/
iphone6s/
motog6/
motog7/
我看到 bash 扩展 here .我错过了什么?也许只有交互式 shell 的一些默认值?
Minimal, complete and verifiable example (感谢@kamil-cuk):
$ D=a/; echo ${D%%+(/)}; bash <<<'D=a/; echo ${D%%+(/)}'
a
a/
最佳答案
来自bash manual :
If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized. ...
+(pattern-list)
Matches one or more occurrences of the given patterns.
您需要在脚本中启用 extglob
shopt
选项以使用扩展模式匹配运算符 +(/)
。
echo 'shopt -s extglob; for D in */; do echo ${D%%+(/)} ; done' > test.sh
关于linux - Bash 扩展 : Different results when running file or running in terminal//extglob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56890095/