Re: double "triangle" loop for $* ?
2006-10-31, 16:11(-08), Yakov:
> I'm curious how to write the double "triangle" loop for $* in posix sh
> analogous to this loop: for(k=0; k<N;k++) for(j=0; j<k; j++) body;
> preferably in posix shell. I'm experienced shell scripter but here,
> I'm stumped: for x in $*; do for y in ????; do body; done; done;
> (???? must become the slice of $* list from $1 to one before
> the element represented by $x)
>
> Is it possible at all ? bash-specific solutions are welcome, too,
> but posix sh are preferred.
[...]
for x in $*
is not correct. the "*" variable contains the concatenation of
the positional parameters with spaces. As you left it unquoted
it is split against spaces (the ones used for concatenation and
the one in the positional parameters themselves)tabs and newline
characters, and filename generation is performed (? is expanded
to the list of single character files in the current directory
for instance).
The syntax is
for i do ...; done
or
for i in "$@"; do ...; done
You can do:
k=1
while [ "$k" -le "$#" ]; do
eval "arg_k=\${$k}"
j=1
while [ "$j" -lt "$k" ]; do
eval "arg_j=\${$j}"
# body
j=$(($j + 1))
done
k=$(($k + 1))
done
Or:
k=0
for arg_k do
j=0
for arg_j do
[ "$j" -ge "$k" ] && break
# body
j=$(($j + 1))
done
k=$(($k + 1))
done
--
Stéphane
|