bash - 为什么我得到 "syntax error near unexpected token ` (' "?

标签 bash unix

我想遍历许多目录并删除除满足特定条件的文件之外的所有文件。我有以下 bash 脚本:

#!/bin/bash
for i in */
do
  cd $i
  rm !(*M.*)
  cd ..
done

但是,当我运行脚本时,出现以下错误:

script1.sh: line 5: syntax error near unexpected token `('
script1.sh: line 5: `    rm !(*M.*)'

有什么问题吗?我正在使用 Ubuntu 14.04。

感谢您的帮助。

最佳答案

我认为您应该启用 extglob 以使用反转或负通配符:

shopt -s extglob

请注意,您可以一直保持此状态,它没有害处。

也就是说,您不必在代码中使用循环,可以直接放入脚本中:

rm */!(*M.*)

您可以访问此帖子以获取其他解决方案: https://unix.stackexchange.com/questions/78376/in-linux-how-to-delete-all-files-except-the-pattern-txt

关于bash - 为什么我得到 "syntax error near unexpected token ` (' "?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33924985/

相关文章:

linux - 如何查看 linux 中的磁盘利用率趋势(特别是 centos)

java - runtime.getruntime.exec 的内存问题

unix - sed/awk : Insert some text in a file after the last pattern found

c++ - 如何共享我的 C/C++ 项目并隐藏部分源代码?

bash - unix shell子字符串?

linux - bash脚本测试字符串上多个参数的条件

linux - 追加到 bash 中的最后一行

bash - POSIX 兼容的 shell 相当于 Bash "while read -d $'\0' ..."?

unix - 如何在同一行中grep三个表达式

计算 UNIX 进程时间溢出之前还有多少天