I am trying to move my file to another system which is located in some other place, with this command:

rsync -avrz  src destination

It works fine. But what I need is to put this command in shell script and run it like:

#! /bin/sh
rsync -avrz  srcfilelocation destination

When it runs, it asks for the destination system password. I know that password and give it manually.

Now I have decided to assign the password to an environment variable, like pswd="destination system password". I need my shell script to read the password from this variable. How can I write a script to do this?


You don't need to worry about passwords when you can use something called Public Key Infrastructure.

This is a method of using public and private keys to authenticate a user. You store a copy of your private key, and the other server has a copy of your public key. When you log in, they have a little conversation with each other which confirms the public and private keys match so you can log in without entering a password.

This is as secure as anything as long as you don't share your private key with anyone!

To set this up is really simple.

On source machine, run ssh-keygen. You can accept all the defaults, that'll be enough for this purpose. It'll generate your private (id_rsa) and public(id_rsa.pub) keys in your ~/.ssh folder.

Now you want to get the public key on the server, which is easy too.

From the source pc, run ssh-copy-id username@servername.

This will place a copy of id_rsa.pub's content in the server's ~/.ssh/authorized_keys.

Now if you ssh from the source to the destination you will get in without requiring a password.

How does this affect rsync I hear you ask? Rsync uses ssh!

Please remember: NEVER GIVE OUT YOUR PRIVATE KEY (id_rsa) or someone can pretend to be you.

  • Its not work in my ubuntu 10.04 system. After did all the above steps, since it ask password. – Viswa Jul 10 '12 at 14:14

I do recommend using PKI/SSH keys over doing this but if you need to you can set an environment variable like so:

export RSYNC_PASSWORD="yourPasswordHere"

Please note that this does have some potential security implications and will only be available in the current session.

To add this to a user's session by default:

echo 'export RSYNC_PASSWORD="yourPasswordHere"' >> ~/.bashrc

Alternatively, you can use a password file to store your password. Please note that the password is in plain text, so you should take steps to protect it.

echo "yourPasswordHere" > yourPasswordFile.txt
rsync -avrz --password-file yourPasswordFile.txt src dest

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.