[英]bash how to pass variable to the remote bash script
I have local bash script which is used to invoke a bash script in the remote server and get some reports from remote server.我有本地 bash 脚本,用于调用远程服务器中的 bash 脚本并从远程服务器获取一些报告。
The way I call this script currently in local_script.sh
is:我目前在
local_script.sh
调用这个脚本的方式是:
ssh remoteuse@ip "/bin/bash remote_script.sh"
Now, I want to set a date variable in local_script.sh
file and variable needs to available in remote_script.sh
files also.现在,我想在
local_script.sh
文件中设置一个日期变量,并且变量也需要在remote_script.sh
文件中可用。
Please give some ideas.请给出一些想法。
EDIT :编辑:
Please see my test script:请看我的测试脚本:
[user@localserver]$ ssh remoteusr@ip "/bin/bash remote_script.sh $test_var"
And my remote script:还有我的远程脚本:
[user@remoteserver]$ cat remote_script.sh
#!/bin/bash
echo $test_var > test_var.log
But test_var.log
file on remote server is empty after running the script但是运行脚本后远程服务器上的
test_var.log
文件为空
远程服务器不知道您的本地变量,您只能在 ssh 行使用额外的参数将变量的值从本地传递到远程:
ssh remoteuse@ip "/bin/bash remote_script.sh $variable"
You have to add the variable to the environment of the executed command.您必须将变量添加到已执行命令的环境中。 That can be done with the
var=value cmd
syntax .这可以通过
var=value cmd
语法来完成。
But since the line you pass to ssh
will be evaluated on the remote server, you must ensure the variable is in a format that is reusable as shell input .但由于您传递给
ssh
行将在远程服务器上进行评估,因此您必须确保该变量的格式可作为 shell input 重用。 Two ways come to mind depending on your version of bash
:根据您的
bash
版本,可以想到两种方法:
With bash 4.4
or newer, you can use the Q
operator in ${parameter@operator}
:使用
bash 4.4
或更新版本,您可以在${parameter@operator}
使用Q
运算${parameter@operator}
:
local script:本地脚本:
foo="abc'def \\"123\\" *" ssh remoteuse@ip "foo=${foo@Q} /bin/bash remote.sh"
remote script:远程脚本:
printf '<%s>\\n' "$foo"
output:输出:
$ ./local_script.sh <abc'def "123" *>
If you don't have bash 4.4
or newer, you can use the %q
directive to printf
:如果您没有
bash 4.4
或更高版本,您可以使用%q
指令来printf
:
ssh remoteuse@ip "foo=$(printf '%q' "$foo") /bin/bash remote.sh"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.