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

Deleting everything, except for two files

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

#!/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}"

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