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

Hay*_*yra 6 ssh bash shell

我正在尝试使用ssh连接执行远程本地脚本.我已经阅读了有关它语法的文档.但我的问题是,在运行脚本之前,我需要执行bash和源环境变量.

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

ssh [user]@[server] 'bash -s' < [local_script]
Run Code Online (Sandbox Code Playgroud)

我用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
Run Code Online (Sandbox Code Playgroud)

您对这种远程命令的实现有什么想法吗?我必须在环境设置之前获取配置文件,否则它会给出异常.但主要问题是关于来源.

也许这是一个简单的问题,但我没有任何想法.提前感谢您的所有答案.

Chr*_*ris 6

eval可以为您完成此操作:

eval $(cat /path/to/environment) ./script.sh
Run Code Online (Sandbox Code Playgroud)

如果您知道路径,也可以通过这种方式获取多个文件:

eval $(cat /path/to/environment1 /path/to/environment2) ./script.sh
Run Code Online (Sandbox Code Playgroud)

或者遍历一个目录:

eval $(cat $(find -type f /path/to/environments)) ./script.sh
Run Code Online (Sandbox Code Playgroud)

如果您要远程执行此操作以解决您的特定问题,请将 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
Run Code Online (Sandbox Code Playgroud)

如果您想将远程环境置于您自己的环境中,请在本地使用 eval ,如下所示:

eval "$(ssh user@host cat /path/to/environment)" ./local_script.sh
Run Code Online (Sandbox Code Playgroud)

这使您可以在将调用您的脚本(使它们可用)的同一个分叉实例中获取外部文件设置它的环境变量。

考虑一个看起来像这样的脚本文件:

#!/bin/sh
echo "$VAR1"
echo "$VAR2"
test_function
Run Code Online (Sandbox Code Playgroud)

现在考虑您的环境文件如下所示:

# Environment Variables
VAR1=foo
VAR2=bar
test_function()
{
   echo "hello world"
}
Run Code Online (Sandbox Code Playgroud)

如果您使用 eval 示例,您将看到输出:

foo
bar
hello world
Run Code Online (Sandbox Code Playgroud)

或者,如果您只是打开您编写的脚本,您可以直接从其中获取这些环境变量,然后您可以正常调用脚本而无需任何技巧:

#!/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
Run Code Online (Sandbox Code Playgroud)


Hay*_*yra 0

我通过编写另一个模板脚本来解决该问题,该脚本获取环境变量并运行脚本:

PROFILE=/dir/to/profile/.profile
source $PROFILE
cd /dir/to/script
/bin/bash script $1
Run Code Online (Sandbox Code Playgroud)

如果您在shell中使用该source命令,则不适用于 source 命令。bash#!/bin/bash