如何将变量从一个 shell 脚本返回到另一个脚本

如何将变量从一个 shell 脚本返回到另一个脚本

问题描述:

我有 2 个 shell 脚本,名为 script1.sh(在本地服务器上执行)和 script2.sh(在我将其传递给 ssh 命令的远程服务器上执行).并且我的 script1.sh 正在连接到 unix 服务器并执行 script2.sh,如下所示.

I have 2 shell scripts called script1.sh (executes on local server ) and script2.sh (executes on remote server which i am passing it to ssh command). and my script1.sh is connecting to unix server and and executing script2.sh as below.

declare RESULT=$(sshpass -p 'password' ssh username@1.2.3.4 "bash -s" < ./script2.sh )

和 script2.sh 进行一些计算并返回一些变量来调用脚本,即 script1.sh

and script2.sh does some calculations and returns some variable to calling script i.e script1.sh

#!/bin/sh
declare var1="fgte"
return var1

我想从在服务器上执行的 script2.sh 返回 var1,并且应该向 script1.sh 返回一些值.我怎样才能做到这一点?我需要读取 script1.sh 中 var1 的值.请帮帮我.

I want to return var1 from script2.sh which is executing on server and should return some value to script1.sh. How can i do that? I need to read the value of var1 in script1.sh. Please help me.

最简单的方法是使用 stdout,并将结果打印到你的 script2.sh(使用 echocode> 就像你所做的那样),并将其收集在 script1.sh 中,例如

The simplest way is to use stdout, and print out the result in your script2.sh (using echo as you've done), and collect it in script1.sh e.g.

#!/bin/sh
result=$(script2.sh $var)

当您从子脚本返回多个值时,这会变得更加复杂,并且您必须描述/解析.然而,对于单一价值,这是一种简单实用的方法.

This becomes more complex as/when you return multiple values from a child script, and you have to delineate/parse. For a single value, however, it's a simple and pragmatic approach.

请注意,这与 shell 脚本退出代码不同,后者传统上用于指示您的脚本是否成功返回.

Note this is distinct from the shell script exit code, which is traditionally used to indicate if your script returned successfully or not.