Remove files from remote host using SSH

5

2

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

dimba

Posted 2011-05-25T15:47:00.167

Reputation: 713

1@Wes's answer can be easily adapted to your needs - just add the /* at the end. It's hardly a complex command to understand. – ceejayoz – 2011-05-25T16:21:14.963

Answers

7

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

dimba

Posted 2011-05-25T15:47:00.167

Reputation: 713

15

It's as simple as:

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

Wes Hardaker

Posted 2011-05-25T15:47:00.167

Reputation: 1 796

as with any other command, pratically. Just say ssh hostname, and then the command you want to execute. Very handy for eg. doing remote backups/dumps etc. – None – 2011-05-25T20:38:49.633

1

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.

Igor Feghali

Posted 2011-05-25T15:47:00.167

Reputation: 11

-1

Remove all files from directory hierarchy:

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

techshack

Posted 2011-05-25T15:47:00.167

Reputation: 101

That's very dangerous because it breaks on files with spaces in their name. – slhck – 2014-06-21T14:15:07.973

@slhck Right, one should either not use spaces in filenames or use dimbas's solution which is better. – techshack – 2014-06-23T05:52:16.037

Is there a way to pass in a list of files? I have a folder locally called ./deleteme and I want to delete all files in ./deleteme from the remote server. – chovy – 2013-08-21T04:17:25.353