I want to remove all folder and files except a folder named docs.
echo !(docs)but I got -bash: !: event not found?
I'm using mac default terminal.
61 Answer
You have two issues:
!(doc)is an extended glob andextglobis turned off. If your bash supportsextglob, you can turn it on with:shopt -s extglobHistory expansion is turned on. To turn if off, run
set -HHistory expansion causes surprising things to happen when
!are used. If you do not use history expansion, you can avoid surprises by turning it off.
Example
Let's consider a directory with these files:
$ ls
docs file1 file2Now, let's turn extglob off and history on and run your command:
$ shopt -u extglob; set -H
$ echo !(docs)
bash: !: event not foundThis is exactly the error message that you reported. Thus, this appears to be your situation.
Now, let's keep extglob off and turn history expansion off:
$ shopt -u extglob; set +H
$ echo !(docs)
bash: syntax error near unexpected token `('This error is different from the one you reported. This is not your situation.
Lastly, let's run your command with extglob on. For completeness, we will try history expansion in both settings:
$ shopt -s extglob; set +H
$ echo !(docs)
file1 file2
$ shopt -s extglob; set -H
$ echo !(docs)
file1 file2Both of these work. Thus, as long as your shell supports extglob and has it turned on, your command should work.