代码之家  ›  专栏  ›  技术社区  ›  theomega

Bash:子进程访问变量

  •  3
  • theomega  · 技术社区  · 16 年前

    我构建了下面的脚本。 runonip -函数在子shell中执行,它无法访问 DATA

    代码:

     #!/bin/bash
    set -u
    
    if [ $# -eq 0 ]; then
       echo "Need Arguments: Command to run"
       exit 1
    fi 
    
    DATA=""
    PIDS=""
    
    #Function to run in Background for each ip
    function runonip {
        ip="$1"
        no="$2"
        cmds="$3"
        DATA[$no]=$( {
            echo "Connecting to $ip"
            ssh $ip cat /etc/hostname
            ssh $ip $cmds
        } 2>&1 )
    }
    
    ips=$(get ips somewhere)
    
    i=0
    for ip in $ips; do
        #Initialize Variables
        i=$(($i+1))
        DATA[$i]="n/a"
    
        #For the RunOnIp Function to background
        runonip $ip $i $@ &
    
        #Save PID for later waiting
        PIDS[$i]="$!"
    done
    
    #Wait for all SubProcesses
    for job in ${PIDS[@]}; do
        wait $job
    done
    
    #Everybody finished, so output the information from DATA
    for x in `seq 1 $i`; do
        echo ${DATA[$x]}
    done;
    
    2 回复  |  直到 16 年前
        1
  •  5
  •   Peter Westlake    16 年前

    您需要做的是为这两个进程找到其他的通信方式。以PIDs命名的临时文件是一种方式:

    #For the RunOnIp Function to background
    runonip $ip $i $@ >data-tmp&
    mv data-tmp data-$!
    

    然后对文件进行分类:

    #Everybody finished, so output the information from the temp files
    for x in ${PIDS[@]}; do
        cat data-$x
        rm data-$x
    done;
    
        2
  •  4
  •   Dennis Williamson    16 年前

    你也许可以建立一个 named pipe

    在bash4中,另一种可能是使用 coprocesses .

    推荐文章