2014-01-14 51 views
4

当运行下面的命令:glob模式

rm -rf !(file1|file2) 

所有文件除了文件1和file2被去除;如预期 当任一在bash放置该命令。脚本:

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

或使用bash -c运行它:

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

我收到以下错误:

syntax error ner unexpected token '(' 

我试图设置壳选择使用

shopt -s extglob 

yeilding中: https://superuser.com/questions/231718/remove-all-files-except-for-a-few-from-a-folder-in-unix和一些:

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

根据使水珠其他问题也是如此。

它仍然无法正常工作,而且我很茫然。

回答

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)'