You are not logged in.
I am writing a simple script which uses rsync. Sometimes i want to provide a different port for ssh like this:
rsync -e 'ssh -p 1234' ....
I have a variable for this: $OPT. sometimes this variable is empty, sometimes it contains -e 'ssh -p1234'. But when I try to use this variable bash tries to escape apostrophe like \'
Now my question is how can I put apostrophe in a variable? I have tried the following scenarios and the interpreted command is also shown:
"-e 'ssh -p1234'" -> -e ''\''ssh' '-p1024'\''' (escapes apostrophe)
-e'ssh -p1234' -> -essh -p1024 (ignores apostrophe)
-e"ssh -p1234" -> -essh -p1234 (ignores apostrophe)
-e\"ssh\ -p1234\" -> '-e"ssh' '-p1024"' (escapes only quotation marks)
-e\'ssh\ -p1234\' -> '-e'\''ssh' '-p1024'\''' (escapes only apostrophes)
-e\ ssh\\\ -p1234 -> -e 'ssh\' -p1024 (escapes backslashes)
I'm a few tries away from pulling out my hair, so any help is appreciated.
Offline
$ BLA="ssh -p 1234"
$ echo $BLA
ssh -p 1234
$ echo '$BLA'
$BLA
$ echo \'$BLA\'
'ssh -p 1234'
?
Offline
$ OPT="-e 'ssh -p1234'"
+ OPT='-e '\''ssh -p1024'\'''
$ echo $OPT
+ echo -e ''\''ssh' '-p1024'\'''
'ssh -p1024'
I want to have 2 different spaces in my variable. The first space should separate arguments, but the second one should not. You can see how bash interprets spaces in these examples.
Offline
Use quotes when variable is substituted with it's content:
$ OPT="-e 'ssh -p 1234'"
$ echo rsync "${OPT}"
rsync -e 'ssh -p 1234'
Offline
An array would also work provided it's quoted when used:
rsync_ssh_arg=('-e' 'ssh -p 1234')
rsync "${rsync_ssh_arg[@]}"
POC:
$ array=('e' 'ssh -p 1234')
$ touch "${array[@]}"
$ ls -l
-rw-r--r-- 1 a9 users 0 Mar 4 10:22 e
-rw-r--r-- 1 a9 users 0 Mar 4 10:22 'ssh -p 1024'
$ rm "${array[1]}"
$ ls -l
-rw-r--r-- 1 a9 users 0 Mar 4 10:22 e
The quotes around the array actually result in each indexed item being quoted, so touch/rm see index 1 as a single argument. I changed '-e' to 'e' to avoid the potentially confusing need to pass '--' to touch and rm.
But whether the Constitution really be one thing, or another, this much is certain - that it has either authorized such a government as we have had, or has been powerless to prevent it. In either case, it is unfit to exist.
-Lysander Spooner
Offline