Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Frustrating. The script below work for the first two targets, but not the second.

backitup () {
Todaysdate=`date "+%Y-%m-%dT%H_%M_%S"`
Username=$(echo $Sourcedir | cut -f1 -d'@')
if [ "$Username" = "root" ] ; then
    RSYNCPATH="sudo rsync"

cmd="sudo rsync -vazP --rsync-path='$RSYNCPATH' --log-file=/var/log/rsync.log $Sourcedir /BACKUPS/$Destination/back-$Todaysdate"
                echo $cmd >> ~/cmd.txt
backitup root@HAZns01:/etc "HAZNS01/etc"
backitup root@HAZns01:/home/ftpusers "HAZNS01/ftpusers"
backitup jakadmin@HAZFAND10:/etc "HAZFAND10/etc"
backitup jakadmin@HAZFAND11:/etc "HAZFAND11/etc"

The second two calls give:

unexpected remote arg: jakadmin@HAZFAND10:/etc

If however I run then run the contents of cmd.txt manually from the commandline (bash cmd.txt) then it runs fine. How can that be? (I've got passwordless ssh all setup correctly of course)

What am I missing?

share|improve this question

migrated from serverfault.com May 28 '13 at 5:11

This question came from our site for system and network administrators.

Opps! Added a couple of lines to make this clearer – snori74 May 27 '13 at 23:16

Please see BashFAQ/050.

This fails because of WordSplitting and because the single quotes inside the variable are literal; not syntactical.

You should avoid putting commands in variables when shell scripting.

Use a function to be able to reuse a command. Use set -x for logging. Or use an array to hold the individual parts of the command and its arguments only if you must.

By the way, in one line you use $() for command substitution. This is the correct way. In another line you use backticks which is deprecated. At least be consistent.

share|improve this answer
Thanks very much for that - will be testing shortly! – snori74 May 28 '13 at 2:50
All working now! Took out the "cmd=" stuff, replaced '$RSYNCPATH' with "rsync" or "sudo rsync" depending on some ugly if/then/else. Nice task to refactor another day :-) – snori74 May 28 '13 at 8:44

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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