7

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
  • 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
    May 25, 2011 at 16:21

4 Answers 4

17

It's as simple as:

ssh HOSTNAME rm -rf "/path/to/the/directory/*"
1
  • 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.
    – Anonymous
    May 25, 2011 at 20:38
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

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.

-1

Remove all files from directory hierarchy:

ssh user@HOSTNAME 'rm $(find /path/to/directory -type f)' 
3
  • 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
    Aug 21, 2013 at 4:17
  • That's very dangerous because it breaks on files with spaces in their name.
    – slhck
    Jun 21, 2014 at 14:15
  • @slhck Right, one should either not use spaces in filenames or use dimbas's solution which is better.
    – techshack
    Jun 23, 2014 at 5:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .