linux - Bash 扩展 : Different results when running file or running in terminal//extglob

标签 linux bash

在某些脚本中,我想使用当前文件夹中的文件夹名称。我想获取文件夹名称,这里我只会把有问题的部分放在例子中。如果我从终端运行它,我会得到:

$ 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/

相关文章:

linux - 自定义别名的 Bash cd 命令自动完成

git - 在 git init 上执行脚本

regex - 如何在脚本中使用正则表达式来 gzip 日志文件

javascript - 为什么我无法响应 Node JS 中子进程的输出?

bash - 在 bash 中使用变量参数和输入文件名命名输出文件

linux - 如何在 Shell 脚本中执行 For 循环而不是 While 循环

linux - ls 命令的前两个结果

没有 'video system' 的 Python GUI

c - 为目标文件中的指令分配地址

linux - 开启 fanotify 时多线程打开文件挂起