0

I am trying to come up with a Shell script that can tar a file and copy (scp?) it from Host A to a remote host B at a particular destination /foo, and rename it to a particular time format we use let's say YYYY-MM-DD.

Now to add to this functionality let's say there's a file foo.txt that is copied from Host A to a path on Host B on a particular date, this of course accomplished by the script. Now in case this script is run twice on the same day, instead of overwriting the existing file on remote Host B this script has to identify that a version already exists on Host B and instead of overwriting it, has to append the timestamp on the file being copied by let's say "1" and hence copy it as a different file.

For example, if foo.txt already exists on Remote Host B, the script that's run from Host A should rename the file to foo.txt.1 and copy it onto the same path on remote host B.

Since it's only one file I am fine using SCP over rsync.

2

If I understand well your request, you just need an rsync option: --backup (or -b).

Taking a look at rsync manpage:

-b, --backup
With this option, preexisting destination files are renamed as each file is transferred or deleted. You can control where the backup file goes and what (if any) suffix gets appended using the --backup-dir and --suffix options.

So, if you are planning to transfer the file foo.txt to the folder /foo, from Host1 to Host2, your command could be:

rsync -b --suffix=".$(date +%Y-%m-%d)" -e "ssh -p $SSH_SERVER_PORT" foo.txt remoteuser@Host2:/foo/foo.txt  

Each time you will copy the file "foo.txt" onto Host2, you will get a new file "foo.txt.YYYY-MM-DD".
Consider using the option --backup-dir to keep all backupped versions of your file in the same place.

  • Pay attention: you will have just 1 backup copy a day for each file, because of your choice of suffix. If you want to keep "all" backup copies, consider using another suffix option (date +%Y-%m-%d_%H%M%s could be an idea)
  • I tried doing this, however what I have noticed is that this actually just takes a back of it on the existing server itself and doesn't copy it to the remote server. For example after I run this command, it's just making a backup version of the file in the server I run this command in it doesn't copy it to the remote host that I wanna copy this to. – S K Kumar Sep 14 '16 at 20:23
  • Could you paste here your customized line of code (with fake usernames and server addresses) and the output of that using the -vvv option? It's really strange this behaviour because of the rsync syntax: (PUSH) rsync [OPTION...] SRC... [USER@]HOST:DEST – Echoes_86 Sep 15 '16 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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