UPDATE: I've been testing this further...It is behaving oddly!!, or as you mention, it may not be the right syntax contortion :)
I'm starting to think that this construct is not appropriate for arrays... It works when x
is unset, but I've just discoverd that it behaves oddly when x
is set .. The LHS 'x' is assigned to just the first elemnet of the RHS 'x' array ... Perhaps :=
may do the trick...
UPDATE 2: I'm convinced that this won't work with arrays (but if I'm wrong, it wouldn't be the first time) ... I've added more tests to the script.. and the nett result is that whenever x
is assigned a value via this method, it is only assigned the $x / $x[0] value....
An interesting page: The Deep, Dark Secrets of Bash
#
echo "===============1 'manually' set Y"
i=0; for T in A "B B" "C C C" ; do
Y[$i]="$T"; echo Y[$i]="${Y[i]}" ; ((i++))
done
#
echo "===============2a 'manually' set x"
unset x
i=0; for T in 2 "2 2" "2 2 2" ; do
x[$i]="$T"; echo x[$i]="${x[i]}" ; ((i++))
done
#
echo "===============2b (X is already set); ':-'set to Y array, but should keep previous X vals"
x=("${x:-${Y[@]}}"); for ((i=0;i<${#x[@]};i++)) ; do
echo x[$i]="${x[i]}"
done
#
echo "===============2c (X is unset); ':-'set to Y array, and should take on new Y vals"
unset x
x=("${x:-${Y[@]}}"); for ((i=0;i<${#x[@]};i++)) ; do
echo x[$i]="${x[i]}"
done
#
echo "===============3a 'manually' set x"
unset x
i=0; for T in 3 "3 3" "3 3 3" ; do
x[$i]="$T"; echo x[$i]="${x[i]}" ; ((i++))
done
#
echo "===============3b (X is already set); ':='set to Y array, but should keep previous X vals"
echo "${x:=(${Y[@]})}" >/dev/null ; for ((i=0;i<${#x[@]};i++)) ; do
echo x[$i]="${x[i]}"
done
#
echo "===============3c (X is unset); ':='set to Y array, and should take on new Y vals"
unset x
echo "${x:=(${Y[@]})}" >/dev/null ; for ((i=0;i<${#x[@]};i++)) ; do
echo x[$i]="${x[i]}"
done
echo "==============="
echo
#
The output is:
===============1 'manually' set Y
Y[0]=A
Y[1]=B B
Y[2]=C C C
===============2a 'manually' set x
x[0]=2
x[1]=2 2
x[2]=2 2 2
===============2b (X is already set); ':-'set to Y array, but should keep previous X vals
x[0]=2
===============2c (X is unset); ':-'set to Y array, and should take on new Y vals
x[0]=A
x[1]=B B
x[2]=C C C
===============3a 'manually' set x
x[0]=3
x[1]=3 3
x[2]=3 3 3
===============3b (X is already set); ':='set to Y array, but should keep previous X vals
x[0]=3
x[1]=3 3
x[2]=3 3 3
===============3c (X is unset); ':='set to Y array, and should take on new Y vals
x[0]=(A B B C C C)
===============
:-(
... – l0b0 May 9 '11 at 14:02