I'm trying to delete all files and directories under /path/to/dir/
except for two directories (dir1
and dir2
) from a remote host using SSH. When I run a command similar to this on my local Ubuntu 14.04 box it works as expected:
user@host1:~$ cd /path/to/dir/ && rm -rf !(dir1|dir2)
If I try to execute the same command through SSH on another host with the same directory structure, it fails.
user@host1:~$ ssh user@host2 'cd /path/to/dir/ && rm -rf !(dir1|dir2)'
bash: -c: line 0: syntax error near unexpected token `('
bash: -c: line 0: `cd /path/to/dir/ && rm -rf !(dir1|dir2)'
How should I escape the command to make it work? I thought that using single quotes was enough.
Best Answer
if you really want to use bash patterns you can do this:
I'd rather use find though (append
-delete
if you actually want to delete the files):Example with directories: