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/*.

1

4 Answers

It's as simple as:

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

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

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.

Remove all files from directory hierarchy:

ssh user@HOSTNAME 'rm $(find /path/to/directory -type f)' 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like