Remove files from remote host using SSH

1,494

Solution 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

Solution 2

It's as simple as:

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

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.

Share:
1,494

Related videos on Youtube

Shaun Luttin
Author by

Shaun Luttin

Updated on September 18, 2022

Comments

  • Shaun Luttin
    Shaun Luttin over 1 year

    We have both Visual Studio 2010 and 2012 installed on our machine. Often we want to run it with the devenv command. To be clear, we want to open Visual Studio. How do we pass the version number to run? The devenv command line documentation doesn't say how.

    • ceejayoz
      ceejayoz almost 13 years
      @Wes's answer can be easily adapted to your needs - just add the /* at the end. It's hardly a complex command to understand.
  • Admin
    Admin almost 13 years
    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.
  • chovy
    chovy over 10 years
    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.
  • slhck
    slhck almost 10 years
    That's very dangerous because it breaks on files with spaces in their name.
  • techshack
    techshack almost 10 years
    @slhck Right, one should either not use spaces in filenames or use dimbas's solution which is better.