意外标记“(”附近的语法错误

Tal*_*Tal 12 command-line bash scripts rm

当我在 Ubuntu 终端中使用以下代码时,它工作正常:

rm !(*.sh) -rf
Run Code Online (Sandbox Code Playgroud)

但是,如果我将相同的行代码放在 shell 脚本 (clean.sh) 中并从终端运行 shell 脚本,则会引发错误:

clean.sh 脚本:

#!/bin/bash
rm !(*.sh) -rf
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

./clean.sh: line 2: syntax error near unexpected token `('
./clean.sh: line 2: `rm !(*.sh) -rf'
Run Code Online (Sandbox Code Playgroud)

你能帮我吗?

hee*_*ayl 25

rm !(*.sh)是一种extglob语法,表示删除除具有.sh扩展名的文件之外的所有文件。

在您的交互式bash实例中,shell 选项extglob打开:

$ shopt extglob 
extglob         on
Run Code Online (Sandbox Code Playgroud)

现在,当您的脚本在子 shell 中运行时,您需要extglob通过在脚本开头添加以下内容来启用:

shopt -s extglob
Run Code Online (Sandbox Code Playgroud)

所以你的脚本看起来像:

#!/bin/bash
shopt -s extglob
rm -rf -- !(*.sh)
Run Code Online (Sandbox Code Playgroud)

编辑 :

要删除除.sh扩展名以外的所有文件GLOBIGNORE(因为您不想启用extglob):

#!/bin/bash
GLOBIGNORE='*.sh'
rm -rf *
Run Code Online (Sandbox Code Playgroud)

例子 :

$ ls -1
barbar
bar.sh
egg
foo.sh
spam

$ GLOBIGNORE='*.sh'

$ rm *

$ ls -1
bar.sh
foo.sh
Run Code Online (Sandbox Code Playgroud)