bash中的glob模式不识别'('

时间:2014-01-14 08:12:27

标签: bash glob

运行以下命令时:

rm -rf !(file1|file2)

删除除 file1和file2之外的所有文件;如预期。 将此命令放在bash脚本中时:

#!/bin/bash
rm -rf !(file1|file2)

或使用bash -c:

运行它
bash -c "rm -rf !(file1|file2)"

我收到以下错误:

syntax error ner unexpected token '('

我尝试使用

设置shell选项
shopt -s extglob

yeilding in:

bash -c "shopt -s extglob; rm -rf !(file1|file2)"

根据以下内容启用glob: https://superuser.com/questions/231718/remove-all-files-except-for-a-few-from-a-folder-in-unix以及其他一些问题。

仍然不起作用,我很茫然。

1 个答案:

答案 0 :(得分:6)

首先,为安全起见,让我们使用echo !(file1|file2)代替rm -rf !(file1|file2)进行测试。

无论如何,bash在执行shopt -s extglob命令之前会对整个命令行进行一些解析。当bash遇到(时,extglob选项尚未设置。这就是你得到错误的原因。

请改为尝试:

bash -O extglob -c 'echo !(file1|file2)'

在您的脚本中,您只需在依赖它之前打开该选项作为单独的命令行:

#!/bin/bash
shopt -s extglob
echo !(file1|file2)

您实际上也可以使用-c标志执行此操作:

bash -c 'shopt -s extglob
echo !(file1|file2)'

或者甚至喜欢这样:

bash -c $'shopt -s extglob\necho !(file1|file2)'