【问题标题】:Bash glob pattern behaviour different between terminal and shell script终端和 shell 脚本之间的 Bash glob 模式行为不同
【发布时间】:2017-05-08 05:22:12
【问题描述】:

我有一个 glob 模式 {,**/}*.* 用于递归遍历当前目录中的所有文件以及子目录。如果我在终端中运行echo {,**/}*.*,它会输出当前目录中的所有文件以及嵌套目录。当我运行一个包含这一行的 shell 脚本时,它只做一个目录。

我知道terminal has different behaviour than the shell:添加shopt -s extglob 没有任何区别。

#!/bin/bash

shopt -s extglob
echo {,**/}*.*

我在 MacOSX 上启用了 Bash 4 terminal 和 shopt -s globstar。

【问题讨论】:

  • 如果我添加 shopt -s globstar 会出错:“./show-glob.sh: line 3: shopt: globstar: invalid shell option name”
  • 您确定使用 bash 4 运行它吗?
  • #!/bin/bash on OSX 指向 BASH 3.2 而不是 BASH 4
  • 您可能希望在脚本开头使用#!/usr/local/bin/bash
  • 您是否仍然收到"./show-glob.sh: line 3: shopt: globstar: invalid shell option name" 或其他错误?

标签: bash macos shell terminal glob


【解决方案1】:

{,**/}*.* 不会为您提供当前目录中的所有文件以及子目录。相反,它会为您提供格式结果

directory/file.ext

您可能已经改用./**

如果您使用 globstar,** 将扩展到文件夹中的所有内容。即做

shopt -s globstar
echo ./** # this would suffice

除此之外,借用[ this ]注释,需要使用支持globstar的shell版本。这从你getting

中可以看出来
shopt: globstar: invalid shell option name

那么,

#!/bin/bash -> #!/usr/local/bin/bash

应该做的工作

【讨论】:

  • 根据问题中的 cmets,OP 已在其交互式 shell 中启用 globstar,并在其脚本中启用它时收到错误消息。他的问题与他的shebang有关。
  • @Aserre :我的重点是全局模式。 for recursing through all files in current directory plus children、{,**/}*.*似乎过于复杂。
  • 其实我想包含当前目录,我不要文件夹,所以我的glob是基于stackoverflow.com/a/1691202/158815的答案
  • @mummybot :我明白了,那么你所做的就是完美的方法。
【解决方案2】:

感谢@Aserre 和@anubhava,这确实是 bash 路径和确保启用 globstar 的组合(对于 MacOSX)。完整的脚本是:

#!/usr/local/bin/bash

shopt -s globstar

echo {,**/}*.*

是的,./** 就足够了,但这不是我的问题 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多