Search code examples
bashsshescapingrm

Delete Everything in a Directory Except One FIle - Using SSH


In BASH, the following command removes everything in a directory except one file:

rm -rf !(filename.txt)

However, in SSH the same command changes nothing in the directory and it returns the following error: -jailshell: !: event not found

So, I escaped the ! with \, (the parentheses also require escaping) but it still doesn't work:

rm -rf \!\(filename.txt\)

It returns no error and nothing in the directory changed.

Is it even possible to run this command in SSH? I found a workaround but if this is possible it would expedite things considerably.

I connect to the ssh server using the alias below:

alias devssh="ssh -p 2222 -i ~/.ssh/private_key user@host"

Solution

  • !(filename.txt) is an extglob, a bash future that might have to be enabled. Make sure that your ssh server runs bash and that extglob is enabled:

    ssh user@host "bash -O extglob -c 'rm -rf !(filename.txt)'"
    

    Or by using your alias:

    devssh "bash -O extglob -c 'rm -rf !(filename.txt)'"
    

    If you are sure that the remote system uses bash by default, you can also drop the bash -c part. But your error message indicates that the ssh server runs jailshell.

    ssh user@host 'shopt -s extglob; rm -rf !(filename.txt)'
    devssh 'shopt -s extglob; rm -rf !(filename.txt)'