2

I read old topic

And try do the same rsync with options as variable But I get Warning: Identity file $myVar/ssh_key/my_ssh_key not accessible: No such file or directory. My code

options=(-rvz -e 'ssh -p 22 -i "$myVar"/ssh_key/my_ssh_key -o StrictHostKeyChecking=no')
rsync "${options[@]}" /home/user/proj/ pi@${IP}:/home/pi/proj/

Where $myVar is /home/user/proj/

${IP} is IP address 192.168.1.222

Warning: Identity file $myVar/ssh_key/my_ssh_key not accessible: No such file or directory.

This line without $myVar works good

rsync -rvz -e 'ssh -p 22 -i /home/user/proj/ssh_key/my_ssh_key -o StrictHostKeyChecking=no' --progress /home/user/proj/ pi@${IP}:/home/pi/proj/

How I can do rsync with options as variable?

  • Variables are not expanded within single quotes. You have an opening single quote just in front of _ssh_, which gets closed just after _=no_. – user1934428 May 02 '23 at 08:16

1 Answers1

4

If you place $myVar inside single quotes, it will not be expanded, resulting in the wrong argument being passed to ssh.

To expand it while accounting for possible special characters (spaces and quotes):

options=(-rvz -e "ssh -p 22 -i ${myVar@Q}/ssh_key/my_ssh_key -o StrictHostKeyChecking=no")
rsync "${options[@]}" /home/user/proj/ pi@${IP}:/home/pi/proj/

Why it works: ${options[2]} is built by concatenating 3 sections:

  1. ssh -p 22 -i (the command line before the variable)
  2. ${myVar@Q} (the expanded variable in a quoted format, documented here)
  3. /ssh_key/my_ssh_key -o StrictHostKeyChecking=no (the rest of the arguments)

For older bash versions without @Q support:

options=(-rvz -e "ssh -p 22 -i $(printf %q "${myVar}")/ssh_key/my_ssh_key -o StrictHostKeyChecking=no")
Sir Athos
  • 9,403
  • 2
  • 22
  • 23