【问题标题】:How to pass VAR from child script to parent's script running loop如何将 VAR 从子脚本传递到父脚本运行循环
【发布时间】:2019-03-26 15:02:42
【问题描述】:

我正在考虑如何在以下示例中解决此功能:

#!/bin/bash

. script.sh &

while [ "$VAR" != "OK" ];
do
    echo -e "Waiting..."
    sleep 1
done

脚本.sh

#!/bin/bash
export VAR=OK

由于 while 循环在其父 shell 的子 shell 中运行,它永远不会结束,因为永远不会得到源代码 script.sh export VAR=OK

知道如何将 VAR 值传递给 while 循环吗?

注意:我需要在后台运行 script.sh

谢谢!

【问题讨论】:

  • 我建议让父脚本在每次循环中检查文件是否存在,如果存在则读取内容。然后它可以删除该文件。让子进程写入文件。
  • 您是在等待孩子完成,还是等待孩子为您提供一些数据? while 循环在等待时会做其他事情吗?

标签: bash shell loops variables


【解决方案1】:

孩子

#!/bin/bash
sleep 2                   # wait 2 seconds
echo "OK"

父母

#!/bin/bash
answer=$(mktemp)          # create a tempfile
./script.sh & >$answer    # start script in background, output in tempfile
wait $!                   # wait for script.sh finished
var=$(cat $answer)        # read anwser in variable 
echo $var                 # echo anwser
rm $answer                # cleanup - remove tempfile

【讨论】:

    【解决方案2】:

    这应该做你想做的:

    孩子:

    sleep 1
    echo blah >> $varfile
    

    父母:

    #make sure varfile exists and is empty..
    echo > varfile
    
    #run script in background
    ./script.sh &
    
    # wait for some output:
    VAR=$( ( tail -f varfile & )  | sed "/.*$/q")
    echo >> varfile;
    

    这里只是解释一点诡计:

    tail -f 用于捕获输出。此调用在到达文件末尾时不会终止,而是坐下来等待更多内容写入文件(这是您想要的......起初......)。当它收到一个完整的行时,它将输出它,然后等待下一行。诀窍是它在正常情况下不会终止。相反,它将继续运行,直到有人执行 ctrl-c 或检测到管道损坏。这必须被推送为后台任务,否则脚本中的命令将永远不会终止。它的输出通过管道传输到sed。另一方面,sed 将在它接收到有效的输入结束时终止(由于模式中的 $),并且当它接收到时,脚本继续执行。但请注意,task 此时仍在运行,并将继续运行,直到它尝试将某些内容推送到现在已损坏的管道。为了防止它无限期地运行,我们在 sed 终止后向它输出一些东西,此时它意识到管道已损坏并终止。

    【讨论】:

      【解决方案3】:

      Unix/Linux 系统对进程间通信有很好的支持。在这种情况下,我认为您正在寻找的是信号。例如,您可以执行以下操作:

      foo &
      FOO_PID=$!
      # do other stuff
      kill $FOO_PID
      

      如果在进程退出之前循环完成很重要,您可以trap该信号并在收到该信号时设置VAR=OK

      【讨论】:

        【解决方案4】:

        您可以使用流程替换来实现此目的

        #!/bin/bash
        
        VAR=$(. script.sh &)
        
        while [ "$VAR" != "OK" ];
        do
            echo -e "Waiting..."
            sleep 1
        done
        
        

        脚本.sh

        $VAR=OK
        echo $VAR
        

        【讨论】:

          【解决方案5】:

          parent.sh

          #!/bin/bash
          
          while :
          do
             if [ -e /tmp/var_file ]; then
                VAR=$(cat /tmp/var_file)
                echo "VAR is $VAR"
                rm -f /tmp/var_file
             fi
             sleep 1
          done
          

          child.sh

          #!/bin/bash
          
          echo "SUCCESS" > /tmp/var_file
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-09-20
            • 1970-01-01
            • 2021-02-15
            • 2016-10-29
            • 1970-01-01
            • 1970-01-01
            • 2022-08-24
            • 2022-09-27
            相关资源
            最近更新 更多