在远程计算机上运行本地脚本之前,源环境变量并执行bash

在远程计算机上运行本地脚本之前,源环境变量并执行bash,bash,shell,ssh,Bash,Shell,Ssh,我正在尝试使用ssh连接执行远程本地脚本。我读过一篇关于它的语法的文档。但我的问题是,在运行脚本之前,我需要执行bash和源环境变量 这看起来适合我,但它没有源命令: ssh [user]@[server] 'bash -s' < [local_script] ssh[user]@[server]'bash-s'

我正在尝试使用ssh连接执行远程本地脚本。我读过一篇关于它的语法的文档。但我的问题是,在运行脚本之前,我需要执行bash和源环境变量

这看起来适合我,但它没有源命令:

ssh [user]@[server] 'bash -s' < [local_script]
ssh[user]@[server]'bash-s'<[local\u script]
我用EOF试过这样的方法,但对我也不起作用:

#!/bin/bash
/usr/bin/ssh  "$user@$$host" <<EOF
bash -s
source /dir/to/profile/.profile
source /dir/to/env/set/env.sh
/path/to/script/script.sh stop
EOF
#/bin/bash

/usr/bin/ssh“$user@$$host”我修复了编写另一个模板脚本的问题,该脚本将源环境变量并运行该脚本。希望它能起作用

PROFILE=/dir/to/profile/.profile
source $PROFILE
cd /dir/to/script
/bin/bash script $1
如果在bash shell中使用source命令,#/bin/bash不适用于源命令


谢谢您的评论。

我知道它很旧,但我想补充一点,它不需要额外的文件就可以完成-使用“\”来转义本地变量和远程命令替换-即:

ssh me@somehost "RMTENV=\$(ls /etc/profile) && source \$RMTENV"

我使用它来执行远程java命令,并需要ENV来查找java。

eval可以为您完成以下任务:

eval $(cat /path/to/environment) ./script.sh
如果您知道有多个文件,您也可以通过这种方式来获取多个文件 路径:

或在目录上迭代:

eval $(cat $(find -type f /path/to/environments)) ./script.sh
如果要远程执行此操作以解决特定问题,请将SSH放在它前面:

# note the quotes otherwise we'll source our local environment
ssh user@host "'eval $(cat /path/to/environment)' ./remote_script.sh"

# If it's a local environment you want to sort, then do the same
# command without the quotes:
ssh user@host "eval $(cat /path/to/environment)" ./remote_script.sh
如果您想将远程环境源代码添加到您自己的环境中,请使用eval 因此,在当地:

eval "$(ssh user@host cat /path/to/environment)" ./local_script.sh
这要求您在调用脚本的同一个分叉实例(使它们可用)中设置外部文件的环境变量

考虑如下所示的脚本文件:

#!/bin/sh
echo "$VAR1"
echo "$VAR2"
test_function
# Environment Variables
VAR1=foo
VAR2=bar
test_function()
{
   echo "hello world"
}

现在考虑你的环境文件是这样的:

#!/bin/sh
echo "$VAR1"
echo "$VAR2"
test_function
# Environment Variables
VAR1=foo
VAR2=bar
test_function()
{
   echo "hello world"
}
如果使用eval示例,您将看到输出:

foo
bar
hello world
或者,如果您只是打开您编写的脚本,您可以使用源代码 这些环境变量直接来自它内部,然后您可以 正常调用脚本,无需任何技巧:

#!/bin/sh

# Source our environment by starting with period an then following
# through with the full path to the environment file. You can also use
# the 'source' keyword here too instead of the period (.).
. /path/to/environment

echo "$VAR1"
echo "$VAR2"
test_function

也许
-t
选项将有助于初始化登录shell中的环境<代码>sshuser@server“bash-t-c local_script”
第一个示例和第二个示例的区别在于,第一个示例作为远程命令运行
bash-s
,并将脚本作为输入发送给它,而第二个示例将四行文本作为标准输入发送给远程主机上的默认命令/shell。如果在第二个示例中将
bash-s
移动到命令位置,是否有效?其中两个解决方案无效,我尝试了很多方法,但都无效!!:(像
/dir/to/profile/.profile
这样的文件是否存在于本地计算机上或远程计算机上?——因为它们现在的使用方式假定它们存在于远程计算机上。它们存在于远程计算机上