I need to delete all files inside remote directory using ssh

Tnx

P.S.

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

link|improve this question
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 '11 at 16:21
feedback

migrated from stackoverflow.com May 25 '11 at 20:46

This question came from our site for professional and enthusiast programmers.

4 Answers

It's as simple as:

ssh HOSTNAME rm -rf "/path/to/the/directory/*"
link|improve this answer
beat me to it!! – Anonymous May 25 '11 at 15:49
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 '11 at 20:38
feedback

Remove all files from directory hierarchy:

ssh user@HOSTNAME 'rm $(find /path/to/directory -type f)' 
link|improve this answer
feedback
up vote 0 down vote accepted

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

link|improve this answer
feedback

I can't vote it up, but the answer from idimba is exactly what I use for the same function. The command does not have to be 'rm' as you can do other things too. Additionally, instead of the 'find' command you can execute scripts/commands on the remote server by encapsulating it in quotes so it is passed to the remote shell. Note: doing that disconnects your local script from any logging so it's always nice to log a few details on the remote side (and if you're clever) scp that log file back to a suitable location on your local machine. This makes scripting the whole thing easier and when something goes wrong you have a bit of logging to figure it out. That's even more important if you have multiple scripts running under the same user name. No matter how nice it is to get something working, it's always more satisfying to be able to know what went wrong when it does go wrong. :)

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.