Passing variables in remote ssh command

2019-01-30 17:21发布

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 ?

4条回答
该账号已被封号
2楼-- · 2019-01-30 17:48

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

查看更多
再贱就再见
3楼-- · 2019-01-30 17:56

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.

查看更多
Explosion°爆炸
4楼-- · 2019-01-30 18:02

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.

查看更多
放我归山
5楼-- · 2019-01-30 18:04

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
查看更多
登录 后发表回答