Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

#!bin/bash
...
backitup () {
Todaysdate=`date "+%Y-%m-%dT%H_%M_%S"`
Sourcedir=$1
Destination=$2
Username=$(echo $Sourcedir | cut -f1 -d'@')
if [ "$Username" = "root" ] ; then
    RSYNCPATH="rsync"
else
    RSYNCPATH="sudo rsync"
fi

cmd="sudo rsync -vazP --rsync-path='$RSYNCPATH' --log-file=/var/log/rsync.log $Sourcedir /BACKUPS/$Destination/back-$Todaysdate"
                echo $cmd >> ~/cmd.txt
                $cmd
...
}
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 professional system and network administrators.

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

1 Answer 1

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

 
discard

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.