failed to delete multiple folders inside one folder except 3 folders using rm

89 Views Asked by At

I am trying to delete all folders inside a folder except 2 3 using rm. But, command doesnt work with below error

enter image description here

Tried using escape character, but it will not delete folders.

enter image description here

Any solutions?

EDIT 1

enter image description here

Using double quotes after parentheses is a not working

EDIT 2

using shopt is also not working

enter image description here

1

There are 1 best solutions below

9
Ben Merryman On

Note 1: Shell Option needs to be set first for extglob. I had the same issue running my script until I added it to my .sh file. Link below is a reference from Unix stack exchange.

https://unix.stackexchange.com/questions/153862/remove-all-files-directories-except-for-one-file

Full Working Script: test.sh

shopt -s extglob;
cd Test;
rm -rfi !("atest3"|"atest2")

Note 2: If working in Ansible, the default shell is SH vs BASH. Due to this, you may need to call the script with BASH or use solutions found in this answer to get it working. The script below works in BASH. In ZSH it may require a setopt command similar to extglob.

Script call from SH basic terminal using bash

The following command will remove (rm) by force (f) recursively (r) and interactively (i) all files or folders except (! bang operator) for the file or folders strings ('arg1'|'arg2'|...) listed as piped (|) arguments.

If a nested files and folders is passed as an arg, but the parent is not, that file or folder will be deleted:

rm -rfi !('atest2'|'atest3')

Example of using rm with -rf flags and bang operator to prevent passed string arguments being deleted

I am leaving the below commands as examples from an earlier answer I wrote.

This command will create multiple folders:

mkdir {test1,atest2,atest3,atest4}

And this command will remove the folders:

rm -rfi {test1,atest2,atest3,atest4}

Example of mkdir with args and rm -rfi with args shell command