简体   繁体   English

将局部变量传递给远程shell bash脚本

[英]Passing local variable to remote shell bash script

Trying to pass local variable to remote shell using bash script. 尝试使用bash脚本将本地变量传递给远程shell。 Here is what I am trying. 这是我正在尝试的。 This is test.sh 这是test.sh

#!/bin/bash

envi=$1

function samplefunction {
                        echo "Environment selected is $envi"
                        }

if [ "$envi" = "test" ]; then
   ssh user@remotehost <<EOF
   $(typeset -f samplefunction)
   samplefunction
EOF

else
 echo "Please pass correct parameter which is - test"
fi

When I try to execute "./test.sh test" the result I am getting is "Environment selected is". 当我尝试执行“ ./test.sh测试”时,得到的结果是“选择的环境为”。 shell is not able to pass the variable to the remote system. shell无法将变量传递给远程系统。

ssh does not (and can't) make such variables available on the remote side. ssh不会(也不能)使此类变量在远程端可用。

You can instead embed the definition just like you embedded your function: 相反,您可以像嵌入函数一样嵌入定义:

ssh user@remotehost <<EOF
   $(declare -p envi)
   $(typeset -f samplefunction)
   samplefunction
EOF

You can also copy all known variables. 您也可以复制所有已知变量。 In that case it helps to squash the errors about setting read-only values: 在这种情况下,有助于消除有关设置只读值的错误:

ssh user@remotehost <<EOF
   {
     $(declare -p)
   } 2> /dev/null
   $(typeset -f samplefunction)
   samplefunction
EOF

If you have a specific variable you frequently want to copy, you can choose to have ssh send it automatically by adding SendEnv envi to your ssh config. 如果您有一个经常要复制的特定变量,则可以通过将SendEnv envi添加到ssh配置中来选择使ssh自动发送它。 The variable must be exported for this to work. 必须导出该变量才能起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM