Passing variables in remote ssh command
The list of accepted environment variables on SSHD by default includes LC_*
. Thus:
LC_MY_BUILDN="1.2.3" ssh -o "SendEnv LC_MY_BUILDN" ssh-host 'echo $LC_MY_BUILDN'
1.2.3
Variables in single-quotes are not evaluated. Use double quotes:
ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"
The shell will expand variables in double-quotes, but not in single-quotes. This will change into your desired string before being passed to the ssh
command.
If you use
ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"
instead of
ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'
your shell will interpolate the $BUILD_NUMBER
before sending the command string to the remote host.
(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)
You can feed data right through the standard input of the ssh
command and read
that from the remote location.
In the following example,
- an indexed array is filled (for convenience) with the names of the variables whose values you want to retrieve on the remote side.
- For each of those variables, we give to
ssh
a null-terminated line giving the name and value of the variable. - In the
shh
command itself, we loop through these lines to initialise the required variables.
# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb
# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
FOO
BAR
)
for name in "${VAR_NAMES[@]}"
do
printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
while read -rd '"''"' name value
do
export "$name"="$value"
done
# Check
printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'
Output:
FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]
If you don’t need to export
those, you should be able to use declare
instead of export
.
A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:
$ ssh [email protected] 'read foo' <<< "$foo"