[comp.unix.questions] K-shell variables & Do-loops

dallasb@ntpdvp1.UUCP (Dallas Braxton) (02/09/90)

I'm writing a shel script using K-shell with do loops,
and I want to be able to "export" variables from the loop
to the main body. Example:

var1=yes
# ...
i=1
while i<2
do
# ...
	var1=no
	i=i+1
# ...
done
echo $var1

I get "yes".  How does one get "no"?

Dallas Braxton
Reply by e-mail to: ...!uunet!mcnc!rti!ntpdvp1!dallasb

kgallagh@digi.UUCP (Kevin Gallagher) (02/11/90)

In article <339@ntpdvp1.UUCP> dallasb@ntpdvp1.UUCP (Dallas Braxton) writes:
>I'm writing a shel script using K-shell with do loops,
>and I want to be able to "export" variables from the loop
>to the main body. Example:
>
>var1=yes
># ...
>i=1
>while i<2
>do
># ...
>	var1=no
>	i=i+1
># ...
>done
>echo $var1
>
>I get "yes".  How does one get "no"?
>

The line

	while i<2

is incorrect syntax.  Ksh attempts to find a file of name "2" as input to
command "i" and complains that it cannot find such a file.  Since ksh had an
error executing the do loop, it skips it completely and proceeds to the next
valid line.  You have made an incorrect assumption that the contents of the do
loop were executed.

Try executing the following lines:

var1=yes
# ...
i=1
while test $i -lt 2
do
# ...
  	var1=no
	let "i=i+1"
# ...
done
echo $var1

Note that arithmetic expressions must be executed with a let command.
Check your man pages for the test command.-- 
----------------------------------------------------------------------------
Kevin Gallagher    attctc!digi!kgallagh or attctc.dallas.tx.us!digi!kgallagh
----------------------------------------------------------------------------

jws@hpcljws.HP.COM (John Stafford) (02/13/90)

And beware, if you redirect the input or output of the loop as a whole, you
won't be able to get the variables out at all (as the loop will be executed
by a child shell).