Passing variables in remote ssh command

2019-01-30 17:29发布

问题:

I want to be able to run a command from my machine using ssh and pass through the environment variable $BUILD_NUMBER

Here's what I'm trying:

ssh pvt@192.168.1.133 '~/tools/myScript.pl $BUILD_NUMBER'

$BUILD_NUMBER is set on the machine making the ssh call and since the variable doesn't exist on the remote host, it doesn't get picked up.

How do I pass the value of $BUILD_NUMBER ?

回答1:

If you use

ssh pvt@192.168.1.133 "~/tools/run_pvt.pl $BUILD_NUMBER"

instead of

ssh pvt@192.168.1.133 '~/tools/run_pvt.pl $BUILD_NUMBER'

your shell will interpolate the $BUILD_NUMBER before sending the command string to the remote host.



回答2:

Variables in single-quotes are not evaluated. Use double quotes:

ssh pvt@192.168.1.133 "~/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.



回答3:

As answered previously, you do not need to set the environment variable on the remote host. Instead, you can simply do the meta-expansion on the local host, and pass the value to the remote host.

ssh pvt@192.168.1.133 '~/tools/run_pvt.pl $BUILD_NUMBER'

If you really want to set the environment variable on the remote host and use it, you can use the env program

ssh pvt@192.168.1.133 "env BUILD_NUMBER=$BUILD_NUMBER ~/tools/run_pvt.pl \$BUILD_NUMBER"

In this case this is a bit of an overkill, and note

  • env BUILD_NUMBER=$BUILD_NUMBER does the meta expansion on the local host
  • the remote BUILD_NUMBER environment variable will be used by
    the remote shell


回答4:

Escape the variable in order to access variables outside of the ssh session: ssh pvt@192.168.1.133 "~/tools/myScript.pl \$BUILD_NUMBER"