José Luis
José Luis

Reputation: 3933

rsync in shell for loop

I have this shell script

#!/bin/sh
PATHS=( a b c d )

for PATH in ${PATHS[@]}
do
  rsync -avziP /home/user/$PATH $SERVER:$server_folder -b --backup-dir=$backup_folder/backup_$date --delete --exclude=.* --log-file=$HOME/rsync.log
done

And I always get this error:

rsync: command not found

What is driving me crazy is that if I delete the for loop, and just run the rsync command, the script works perfectly

Upvotes: 3

Views: 2846

Answers (1)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70977

PATH is a reserved variable!

It is the variable specifying where to search tools (like rsync)

$ set | grep ^PATH=
PATH=/home/user/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

Use another variable name!

Avoid full upper case for your own variable names! With the idea that when a variable is full upper case, then it's a system or shell variable!

I like to use camelCase type variable names:

allPaths=( a b c d )
for onePath in "${allPaths[@]}"; do
    rsync -avziP "/home/user/$PATH" "$SERVER:$server_folder" -b \
        --backup-dir="$backup_folder/backup_$date" --delete --exclude=".*" \
        --log-file="$HOME/rsync.log"
done

And keep habit of enclosing your variable in double quotes when used as argument!

Upvotes: 6

Related Questions