Deleting everything, except for two files

87 Views Asked by At

I would like to delete everything in a folder, including folders, except for two files. To do so, why using this script:

#!/usr/bin/env bash

shopt -s extglob
rm !(file1|file2)

Which works, but when i try to execute within a case:

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

This will happen:

test.sh: line 9: syntax error near unexpected token `('
test.sh: line 9: `rm !(file1|file2)'

I would like to know why this, and more important, how to fix :)

2

There are 2 best solutions below

2
On BEST ANSWER

Keep shopt at start of script:

#!/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
1
On

You can do it this simple way.

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

It's very simple, so the script has to be run from the directory in question.