Afficher un message
Vieux 01/11/2006, 02h23   #2
Chris F.A. Johnson
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: double "triangle" loop for $* ?

On 2006-11-01, Yakov wrote:
> 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.


Straightforward POSIX:

k=0
N=666
while [ "$k" -lt "$N" ]
do
j=0
while [ "$j" -lt $k" ]
do
: whatever
j=$(( $j + 1 ))
done
k=$(( $k + 1 ))
done


> 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)


Since you are using $* (instead of "$@", which is probably what you
really want) that is straightforward:

z=
for x in $*
do
z="$z $x"
for y in $z
do
: body
done
done


To use "$@" is more complicated in a POSIX shell, but
straightforward in bash:

unset z
for x in $*
do
z[${#z[@]}]=$x
for y in "${z[@]}"
do
: body
done
done

> Is it possible at all ? bash-specific solutions are welcome, too,
> but posix sh are preferred.


--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
  Réponse avec citation
 
Page generated in 0,05996 seconds with 9 queries