Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

lose varfiable setting in loop 1

Status
Not open for further replies.

AlbertAguirre

Programmer
Nov 21, 2001
273
US
# i set my variable here
thisvar="abc"
echo $thisvar

# i go into my loop here and reset the variable
ls -l |
while IFS=":" read f1 f2
do
thisvar="xyz"
done

# display the supposed reset variable here
echo $thisvar


The result should be xyz but it remains abc

Why???

How can change the variable within the loop???
 
What shell are you using? It's working for me in the Korn Shell.


 

That's a bash shell issue where it create a new process to execute the loop -- bummer. [thumbsdown]

There may be a work-around which I don't remember at this time.
[3eyes]


----------------------------------------------------------------------------
The person who says it can't be done should not interrupt the person doing it. -- Chinese proverb
 
I am indeed using bash.

Can I make it a ksh (#!/bin/ksh) and have it work?

I tried that but no success

Ideas anyone?
 
This:

Code:
  ls -l > /tmp/sometempfile$$
  while IFS=":" read f1 f2
  do
    thisvar="xyz"
  done < /tmp/sometempfile$$
  rm -f /tmp/sometempfile$$

Or if your shell supports process substitution:

Code:
  while IFS=":" read f1 f2
  do
    thisvar="xyz"
  done <(ls -l)

Annihilannic.
 
Hi

Mostly just matter of style, but I prefer it this way, without a temporary file :
Code:
while IFS=":" read f1 f2; do
  thisvar="xyz"
done <<< "$( ls -l )"
This is [tt]bash[/tt] only syntax.

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top