Bash: subprocess access variables

I want to write Bash - Script, which is registered on several machines via ssh and first shows its hostname and executes the command (the same command on each machine). The host name and command output should be displayed together. I need a parallel version, so ssh commands should run in the background and in parallel.

I built bashscripted below. The problem is this: since the function runonipis executed in a subshell, it does not have access to DATA-array to store the results. Is it possible to provide access to the array in some way to the subordinate space, possibly through a "pass by reference" to the function?

the code:

 #!/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;
+3
2

, . , - . Bash .

, . , PID, :

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

cat :

#Everybody finished, so output the information from the temp files
for x in ${PIDS[@]}; do
    cat data-$x
    rm data-$x
done;
+5
+3

Source: https://habr.com/ru/post/1735086/


All Articles