Remove files from remote host using SSH

I need to delete all files inside a remote directory using SSH,

The directory itself must not be deleted, so @Wes' answer is not what I need. If it was a local directory, I would run rm -rf dir/*.


Solution 1:

It's as simple as:

ssh HOSTNAME rm -rf "/path/to/the/directory/*"

Solution 2:

According man of ssh on my machine:

If command is specified, it is executed on the remote host instead 
of a login shell.

This means that shell expansion of command passed by ssh won't be done on remote side. Therefore we need "self contained" command, which doesn't relay on shell expansion.

ssh user@remote-machine "find /path/to/directory -type f -exec rm {} \;"

Here all the job for finding files to be deleted is done exclusively by find, without help from shell.

Some similar question

Solution 3:

This should do the trick:

ssh HOSTNAME "sh -c 'rm -rf /path/to/the/directory/*'"

Note that you need to enclose the remote command with double quotes and the pathname with single quotes.