Search code examples
bashrmextglob

Deleting everything, except for two files


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


Solution

  • 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