Bash 删除所有内容,除了两个文件

Bash 删除所有内容,除了两个文件,bash,rm,extglob,Bash,Rm,Extglob,我想删除文件夹中的所有内容,包括文件夹,除了两个文件。为此,为什么要使用此脚本: #!/usr/bin/env bash shopt -s extglob rm !(file1|file2) 这是可行的,但当我尝试在案例中执行时: #!/usr/bin/env bash read -r -p "Do you want remove everything \ [y/N]: " response case $response in [yY][eE][sS]|[yY]) shop

我想删除文件夹中的所有内容,包括文件夹,除了两个文件。为此,为什么要使用此脚本:

#!/usr/bin/env bash

shopt -s extglob
rm !(file1|file2)
这是可行的,但当我尝试在案例中执行时:

#!/usr/bin/env bash

read -r -p "Do you want remove everything \
[y/N]: " response
case $response in
  [yY][eE][sS]|[yY])
      shopt -s extglob
      rm !(file1|file2)
      ;;
  *)
      printf "Aborting"
      ;;
esac
这将发生:

test.sh: line 9: syntax error near unexpected token `('
test.sh: line 9: `rm !(file1|file2)'
我想知道为什么,更重要的是,如何修复:

在脚本开始时保持shopt:

#!/usr/bin/env bash

shopt -s extglob
read -r -p "Do you want remove everything [y/N]: " response

case $response in
  [yY][eE][sS]|[yY])
      echo rm !(list.txt|file2)
      ;;
  *)
      printf "Aborting"
      ;;
esac

你可以用这种简单的方法来做

#!/usr/bin/env bash

# Here you can insert the confirmation part.

f1=file1
f2=file2

mv "$f1" "/tmp/${f1}$$"    #move f1 to /tmp
mv "$f2" "/tmp/${f2}$$"    #move f2 to /tmp

rm -r ./* #remove everything there is. -r means recursive.

mv "/tmp/${f1}$$" "${f1}"    #move f1 and f2 back
mv "/tmp/${f2}$$" "${f2}"

这非常简单,因此脚本必须从相关目录运行。

您能解释一下原因吗?从case语句内部更改shopt不起作用。它只在放置在case之前时起作用,用bash二进制文件的完整路径替换第一行,并使用选项-例如/bin/bash-iGood的东西。谢谢