【问题标题】:How to use user entered variable value from one shell script to another shell script in linux?如何在linux中使用用户输入的变量值从一个shell脚本到另一个shell脚本?
【发布时间】:2018-10-02 13:48:43
【问题描述】:

我有一个三个 shell 脚本。我必须使用从 script1.sh 到 script2.sh 的用户输入值计数。 如何通过 main.sh 使用从 script1.sh 到 script2.sh 的用户输入值计数?

script1.sh

read -p 'Enter a number:' count

script2.sh

echo "Count:$count"

main.sh

sleep 1 && ./script1.sh
sleep 1 && ./script2.sh

【问题讨论】:

标签: shell


【解决方案1】:

如何在子 shell 中修改全局变量?

这是你真正的问题。

简而言之,你不能!(见here)

您想让main.sh 知道您的变量$count 并由执行script1.sh 的子shell 修改并传递给子shell script2.sh 以供读取。

在使用EXPORT 或将变量声明为全局变量时,可以将变量从父级 (main.sh) 传递给子级以供读取。例如。

#!/usr/bin/env bash
# This is main.sh
export count=5
./script2.sh

#!/usr/bin/env bash
# This is script2.sh
echo "$count"

运行如下:

$./main.sh
5

无法修改变量:

#!/usr/bin/env bash
# This is main.sh
export count=5
./script1.sh
./script2.sh

#!/usr/bin/env bash
# This is script1.sh
count=7

运行如下:

$./main.sh
5

你能做什么?

如果要修改 parent 中的变量,则必须要求 script1.sh 通过 /dev/stdout 返回值,然后将其捕获。

然后你有两个选择:

  • 声明count一个全局变量

    #!/usr/bin/env bash
    # This is main.sh
    export count=5
    count=$(./script1.sh)
    ./script2.sh
    
  • 将count 作为参数传递

    #!/usr/bin/env bash
    # This is main.sh
    count=$(./script1.sh)
    ./script2.sh "$count"
    
    #!/usr/bin/env bash
    # This is my script2.sh
    count="$1"
    echo "$count"
    

运行如下:

$./main.sh
7

另一种解决方案是使用source:

#!/usr/bin/env bash
# This is my main.sh
source ./script1.sh
source ./script2.sh

当您执行脚本时,您正在打开一个新的 shell,在新的 shell 中键入命令,将输出复制回您当前的 shell,然后关闭新的 shell。对环境的任何更改都只会在新的 shell 中生效,并且会在新的 shell 关闭后丢失。

当您获取脚本时,您是在当前 shell 中键入命令。对环境的任何更改都会生效并保留在您当前的 shell 中。

来源:super user: What is the difference between executing a bash script vs sourcing it

【讨论】:

  • 我只想将 count 变量导出到 script2.sh 中,我必须根据该变量做出不同的决定。@kvantour
  • @ARYA1992 我已经修改了答案
  • script1.sh 不仅有计数变量,还有更多的行和变量。我只是作为一个例子给出的。而且我必须执行整个 script1.sh 因为它执行特定的任务1在我必须通过调用 script2.sh 来执行任务 2 之后,我必须使用用户在 script1.sh@kvantour 中输入的计数变量进行决策
猜你喜欢
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多