Your command is storing each whitespace-separated string of the ssh command in an array. So, since you are sshing and then running id
, whoami
and ps aux
, all of their output is added to the array, splitting on whitespace (the default value of the $IFS
variable). You can see this with declare -p ar
:
$ ar=($( ssh localhost sh -c "id;whoami;ps aux")) $ declare -p ar | head -c500 declare -a ar=([0]="uid=1000(terdon)" [1]="gid=1000(terdon)" [2]="groups=1000(terdon),3(sys),7(lp),10(wheel),14(uucp),56(bumblebee),84(avahi),96(scanner),209(cups),995(plugdev)" [3]="terdon" [4]="USER" [5]="PID" [6]="%CPU" [7]="%MEM" [8]="VSZ" [9]="RSS" [10]="TTY" [11]="STAT" [12]="START" [13]="TIME" [14]="COMMAND" [15]="root" [16]="1" [17]="0.0" [18]="0.0" [19]="174456" [20]="11996" [21]="a" [22]="b" [23]="f" [24]="R" [25]="Ss" [26]="Jun23" [27]="7:06" [28]="/sbin/init" [29]="root" [30]="2"
As you can see there, each whitespace-delimited string of the output of each of the commands run is stored in its own array element.
If you want to have an array with only three elements, one per command, you need to use a different character to split on. One way to do this is to edit your commands so that they print a unique character after executing and then use mapfile
to read the array, telling it to split on that unique character. For example, \0
:
$ mapfile -d '' < <( ssh localhost sh -c "id; printf '\0'; whoami; printf '\0'; ps aux") ar $ for i in 0 1 2; do echo "$i: ${ar[i]}"; done | head 0: uid=1000(terdon) gid=1000(terdon) groups=1000(terdon),3(sys),7(lp),10(wheel),14(uucp),56(bumblebee),84(avahi),96(scanner),209(cups),995(plugdev) 1: terdon 2: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 174456 11996 ? Ss Jun23 7:07 /sbin/init root 2 0.0 0.0 0 0 ? S Jun23 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? I< Jun23 0:00 [rcu_gp] root 4 0.0 0.0 0 0 ? I< Jun23 0:00 [rcu_par_gp] root 6 0.0 0.0 0 0 ? I< Jun23 0:00 [kworker/0:0H-kblockd]
declare -p ar
to see the full contents of the array. You might want to redirect that to a file and view it with an editor.declare -p
does not show the exact contents of an array. It show what you would have to type into the shell to create it in the first place. So it includes explicit indexes, quoting and backslash escapes, to conform to shell input rules. Very helpful example, but you need to think what the actual assigned values would be if you intend to process it further.