Issue
I want to pass an array to a script that is on a remote computer. I'm using SSH for this. I tried the below code and I'm getting an error saying that the parameter is not available.
ssh -i location/to/keyfile -o StrictHostKeyChecking=no -T [email protected] ./script.sh -m 1G -s 0 -d 120 -w 60 -j 512M -k 512M -l 515M -b "${array_1[*]}" -u "${array_2[*]}"
Here array_1
and array_2
are indexed arrays.
Solution
If I understand the situation correctly, you have two arrays containing numbers, something like:
array_1=(1 2 3)
array_2=(21 22 23)
...and want to pass those lists of numbers to the script as space-separated lists, something like running this on the remote computer:
./script.sh -m 1G -s 0 -d 120 -w 60 -j 512M -k 512M -l 515M -b "1 2 3" -u "21 22 23"
If this is correct, try the following command:
ssh -i location/to/keyfile -o StrictHostKeyChecking=no -T [email protected] ./script.sh -m 1G -s 0 -d 120 -w 60 -j 512M -k 512M -l 515M -b "'${array_1[*]}'" -u "'${array_2[*]}'"
Explanation: commands passed via ssh get parsed twice; first by the local shell, and then the result of that gets parsed again by the remote shell. In each of these parsing phases, quotes (and escapes) get applied and removed. Your original command had only one level of quotes, so the local shell parses, applies, and removes it, so the remote shell doesn't see any quotes, so it treats each of the numbers as a separate thing.
In more detail: the original command:
ssh -i location/to/keyfile -o StrictHostKeyChecking=no -T [email protected] ./script.sh -m 1G -s 0 -d 120 -w 60 -j 512M -k 512M -l 515M -b "${array_1[*]}" -u "${array_2[*]}"
has the array references expanded, giving the equivalent of (assuming the array contents I listed above):
ssh -i location/to/keyfile -o StrictHostKeyChecking=no -T [email protected] ./script.sh -m 1G -s 0 -d 120 -w 60 -j 512M -k 512M -l 515M -b "1 2 3" -u "21 22 23"
The local shell parses and removes the quotes, but they have the effect of passing 1 2 3
and 21 22 23
to the ssh
programs as single arguments. But then ssh
just pastes the list of command arguments it got back together with spaces in between, so this is what it sends to the remote shell:
./script.sh -m 1G -s 0 -d 120 -w 60 -j 512M -k 512M -l 515M -b 1 2 3 -u 21 22 23
...which confuses the script.
My solution, adding single-quotes around the array references, doesn't change the local parsing (the single-quotes are inside the double-quotes, so they have no special effect); they just get passed through, resulting in this command being sent to the remote shell:
./script.sh -m 1G -s 0 -d 120 -w 60 -j 512M -k 512M -l 515M -b '1 2 3' -u '21 22 23'
The single-quotes here have the same effect that double-quotes would (since there are no other quotes, escapes, dollar signs, or other special characters inside them), so this should give the result you want.
Answered By - Gordon Davisson