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:
set -u
if [ $# -eq 0 ]; then
echo "Need Arguments: Command to run"
exit 1
fi
DATA=""
PIDS=""
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
i=$(($i+1))
DATA[$i]="n/a"
runonip $ip $i $@ &
PIDS[$i]="$!"
done
for job in ${PIDS[@]}; do
wait $job
done
for x in `seq 1 $i`; do
echo ${DATA[$x]}
done;