Linux – SSH remote command with !(pattern-list)

bashlinuxssh

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:

user@remote:~$ ls del/
1  2  3
user@desktop:~$ ssh remote.example 'PATTERN="!(1|2)" bash -O extglob -c "cd del && echo rm \$PATTERN"'
rm 3

I'd rather use find though (append -delete if you actually want to delete the files):

 user@desktop:~$ ssh remote.example 'cd del && find . ! -path . ! \( -name 1 -or -name 2 \)'
./3

Example with directories:

user@remote:~/del$ tree -F
.
├── 1/
│   └── 11/
├── 2/
│   └── 22/
└── 3/
    └── 33/
user@remote:~/del$ find . -maxdepth 1 -type d '!' -path . ! \( -name 1 -or -name 2 \) -print0 | xargs -0 echo rm -r
rm -r ./3
Related Question