【问题标题】:Pattern match does not work in bash script模式匹配在 bash 脚本中不起作用
【发布时间】:2019-08-28 00:38:36
【问题描述】:

使用模式匹配!("file1") 不能在 bash 脚本中使用,但可以在命令行中使用。

例如:

ls  !("file1"|"file2")

这将列出目录中除file1file2 之外的所有文件。

在脚本中执行该行时,将显示此错误:

./script.sh: line 1: syntax error near unexpected token `('
./script.sh: line 1: ` ls  !("file1"|"file2") ' 

无论使用什么rm -v !("file1")。发生同样的错误。这是怎么回事,为什么这在脚本中不起作用?

【问题讨论】:

标签: linux bash glob extglob


【解决方案1】:

默认情况下,您尝试使用的扩展 glob 语法已关闭;您必须在要使用它的每个脚本中单独启用它。

shopt -s extglob

Scripts should not use ls 虽然我想你只是在这里用作占位符。

【讨论】:

    【解决方案2】:

    除非您启用extglob shell opt,否则通配符不起作用。相反,我建议使用find

    find . -maxdepth 1 -not -name '<NAME>' -or -name '<NAME>' -delete
    

    在使用-delete 运行此命令之前,请确保输出正确

    【讨论】:

      【解决方案3】:

      具有默认设置且没有外部过程的方法:

      for f in *; do [[ $f =~ ^file[12]$ ]] || echo "$f"; done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-25
        • 2019-01-22
        • 1970-01-01
        • 2013-07-20
        • 2013-02-08
        • 2019-05-15
        • 2012-07-15
        • 1970-01-01
        相关资源
        最近更新 更多