18
votes

File foo.txt exists on the remote machine at: /home/user/foo.txt

It doesn't exist on the local machine.

I want to delete foo.txt using rsync.

I do not know (and assume for the purposes of this question that I cannot find out) what other files are in /home/user on either the local or remote machines, so I can't just sync the whole directory.

What rsync command can I use to delete foo.txt on the remote machine?

4

4 Answers

30
votes

Try this:

rsync -rv --delete --include=foo.txt '--exclude=*' /home/user/ user@remote:/home/user/

(highly recommend running with --dry-run first to test it) Although it seems like it would be easier to use ssh...

ssh user@remote "rm /home/user/foo.txt"
6
votes

That's a bit trivial, but if, like me, you came to this page looking for a way to delete the content of a directory from remote server using rsync, this is how I did it:

  1. Create an empty mock folder:

    mkdir mock

  2. Sync with it:

    rsync -arv --delete --dry-run ~/mock/ remote_server:~/dir_to_clean/

  3. Remove --dry-run from the line above to actually do the thing.

1
votes

Just came across the same problem, needed to use rsync to delete a remote file, as only rsync and no other SSH commands were allowed. The --remove-source-files option (formerly known as --remove-sender-files) did exactly that:

rsync -avPn --remove-source-files remote:/home/user/foo.txt .
rm foo.txt

As always, remove the -n option to really execute this.

0
votes

As suggested above, use --dry-run to test prior. --delete deletes files on the remote location per the rsync man page.

rsync -rv --delete [email protected]:full/path/to/foo.txt

Comment below stating this will list only is incorrect. To list only use --list-only and remove --delete.