27

I am a unix noob, so please be patient :-)

I have a script that scps a bunch of files to another server.

Suppose they are z1.foo, z2.foo etc. What I want to do is to scp files and delete files older than 5 days in the destination server.

How do I securely delete files from the destination?

Thanks.

Kapsh
  • 519
  • 2
  • 6
  • 7
  • "overwrite the files at the destination"? If you scp files that already exist on the remote dir they'll be overwritten automatically – Aki Jul 10 '14 at 00:11
  • its good idea, to delete the files with a shell script locally.meaning that you are SCPing files whenever you like. but there is shell script which runs on daily basis to remove the files under a certain folder, where you keep the files.command will be something like:`find /path/to/files* -mtime +5 -exec rm {} \;` – Zareh Kasparian Jan 05 '19 at 17:47

3 Answers3

28

To remove files non-interactively:

ssh hostname "rm -f z100.foo z200.foo"
Warner
  • 23,756
  • 2
  • 59
  • 69
11

You could accomplish both tasks in the same command by using the --delete flag to rsync.

> ls -1 localdir/
a.foo
b.foo

> ssh remote-host "ls -1 remotedir/"
c.foo

> rsync -a --delete localdir/ remote-host:remotedir/

> ssh remote-host "ls -1 remotedir/"
a.foo
b.foo

The --delete option removes files from the destination directory that don't exist on the source. There are some choices about when the files are deleted and how to handle excluded files.

> man rysnc
...
--delete                delete extraneous files from dest dirs
--delete-before         receiver deletes before transfer (default)
--delete-during         receiver deletes during xfer, not before
--delete-after          receiver deletes after transfer, not before
--delete-excluded       also delete excluded files from dest dirs

The man page also contains this warning:

This option can be dangerous if used incorrectly! It is a very good idea to run first using the --dry-run option (-n) to see what files would be deleted to make sure important files aren't listed.

Ladadadada
  • 26,337
  • 7
  • 59
  • 90
5

If you would like to set username and port number you can do the following:

ssh root@203.0.113.123 -p22 "rm -rf /home/amzad/test.php"
m82amjad
  • 159
  • 1
  • 2