I have problems with some arrays in bash.
A=( "127.0.0.1" "localhost" "aaa nnn cvcc" )
B=( "8.8.8.8" "dns" "bbb tttt rrrr")
for n in ${A} ${B} ; do
if ping -c3 ${n[0]};then
echo "${n[1]}"
for share in ${n[2]};do
echo $share
done
fi
done
I'd like to print the second and third element of the array but the for loop stop at the ping.
This way it is working.
if ping -c3 ${A[0]};then
echo "${A[1]}"
for share in ${A[2]};do
echo $share
done
fi
I'm sure must be a very silly thing but it is driving me mad…
Some ideas?
Many thanks in advance
Best Answer
Your loop actually loops over the first elements of
A
andB
, i.e.${A[0]}
and${B[0]}
, which later means that${n[1]}
and${n[2]}
would be empty strings while${n[0]}
is the same as$n
.I would probably employ a name reference variable to do this in
bash
(release 4.3 or later):I'm looping over the variable names
A
andB
, not their contents. In the loop, I createarray
as a name reference to the variable named by$variable
. Nowarray
is used exactly as eitherA
orB
.In the
if
statement, I don't rely on the shell to split the third array element for looping. Instead I split it manually when I create theA
andB
arrays and I just output those elements with a single call toprintf
using an offset into thearray
array. I output a tab in front of each element for readability.The
if
statement could also be written asto get the rest of the arrays elements outputted as a comma-delimited list after a colon:
Note: None of the quoting is accidental above. Quoting the expansion of an array ensures that each element is individually quoted. Quoting the expansion of a single element ensures that the shell is not splitting the value on whitespaces (and doesn't do filename globbing on the split-up words).
See also
You could also do this with
/bin/sh
without named arrays. Instead we use the list of positional parameters to hold our data, and terminate each section of that list with a special word (we useEND
, this is an arbitrary string that we choose). We then loop over that list and shift elements off it as we go: