简体   繁体   English

如何从Shell脚本返回特定变量的值?

[英]How to return a specific variable's value from a shell script?

I've got two sh files, which are "main.sh" and "sub.sh" i want to return a variable's value inside "sub.sh" and use it inside main.sh .There is so many "echo" command so i can't just return the value from sub.sh file. 我有两个sh文件,分别是“ main.sh”和“ sub.sh”,我想在“ sub.sh”中返回变量的值并在main.sh中使用它。有很多“ echo”命令所以我不能只从sub.sh文件返回值。 I need only one variable's value. 我只需要一个变量的值。 How can that be possible? 那怎么可能呢?

main.sh main.sh

echo "start"

//how to get a variable from the sh below?
//dene=$(/root/sub.sh)

echo "finish"

sub.sh sub.sh

echo "sub function"
 a="get me out of there"  // i want to return that variable from script
echo "12345"
echo  "kdsjfkjs"

To "send" the variable, do this: 要“发送”变量,请执行以下操作:

echo MAGIC: $a

To "receive" it: 要“接收”它:

dene=$(./sub.sh | sed -n 's/^MAGIC: //p')

What this does is to discard all lines that don't start with MAGIC: and print the part after that token when a match is found. 这样做是丢弃所有不以MAGIC开头的行,并在找到匹配项后在该标记之后打印零件。 You can substitute your own special word instead of MAGIC. 您可以用自己的特殊字词代替MAGIC。

Edit: or you could do it by "source"ing the sub-script. 编辑:或者您可以通过“添加”子脚本来实现。 That is: 那是:

source sub.sh
dene=$a

What that does is to run sub.sh in the context of main.sh , as if the text were just copy-pasted right in. Then you can access the variables and so on. 这样做是在main.sh的上下文中运行sub.sh ,就像将文本复制粘贴到其中一样。然后您可以访问变量,依此类推。

main.sh main.sh

#!/bin/sh

echo "start"

# Optionally > /dev/null to suppress output of script
source /root/sub.sh

# Check if variable a is defined and contains sth. and print it if it does
if [ -n "${a}" ]; then
    # Do whatever you want with a at this point
    echo $a
fi

echo "finish"

sub.sh sub.sh

#!/bin/sh

echo "sub function"
a="get me out of there"
echo "12345"
echo -e "kdsjfkjs"
exit 42

You can export variable to shell session in sub.sh and catch it later in main.sh. 您可以将变量导出到sub.sh中的shell会话中,并稍后在main.sh中捕获它。

sub.sh
#!/usr/bin/sh
export VARIABLE="BLABLABLA"


main.sh
#!/bin/sh
. ./sub.sh
echo $VARIABLE

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

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