简体   繁体   English

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

[英]how to return a variable from one shell script to another script

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). 我有2个称为script1.sh(在本地服务器上执行)和script2.sh(在将其传递给ssh命令的远程服务器上执行)的shell脚本。 and my script1.sh is connecting to unix server and and executing script2.sh as below. 我的script1.sh正在连接到Unix服务器并执行如下的script2.sh。

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

and script2.sh does some calculations and returns some variable to calling script ie script1.sh 然后script2.sh进行一些计算,并将一些变量返回给调用脚本,即script1.sh

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

I want to return var1 from script2.sh which is executing on server and should return some value to script1.sh. 我想从正在服务器上执行的script2.sh返回var1,并且应该向script1.sh返回一些值。 How can i do that? 我怎样才能做到这一点? I need to read the value of var1 in script1.sh. 我需要在script1.sh中读取var1的值。 Please help me. 请帮我。

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 eg 最简单的方法是使用stdout,并在script2.sh打印出结果(完成后使用echo ),然后将其收集在script1.sh例如

#!/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. 但是,对于单个值,这是一种简单而实用的方法。

Note this is distinct from the shell script exit code , which is traditionally used to indicate if your script returned successfully or not. 请注意,这与Shell脚本退出代码不同 ,后者通常用于指示您的脚本是否成功返回。

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

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