2

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

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Replace your first line by full path to bash binary and use option `-i`, e.g. `#!/bin/bash -i` – Cyrus Jul 24 '16 at 15:08

2 Answers2

2

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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.

Cyrus
  • 84,225
  • 14
  • 89
  • 153