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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why does this work in for loop but not in a while loop? 1

Status
Not open for further replies.

RFC1795

IS-IT--Management
Feb 13, 2003
76
US
Hi all,

This one has me stumped. I need to include the following type of test into a script and have it request and input a value should it equal a zero for example.
I couldn't get it working in a while loop, but as soon as I change it to a for loop then it works as I want it to. :-S

Code:
Contents of file.txt:
30
20
50
0
100
85

The while script that doesn't work for me:
Code:
#!/usr/bin/bash

function ZEROTEST {
        if [ "$ARG1" = "0" ]
         then
          echo -n "Enter valid value: " ; read NEWVAL
         ARG1="$NEWVAL"
        fi
}

while read ARG1
 do
  ZEROTEST
  echo "Value : $ARG1"
 done < file.txt

When I run the script, it does not stop and request the new input as I expect it to.

Output:
Value : 30
Value : 20
Value : 50
Enter valid value: Value : 100
Value : 85


This for script works perfectly:
Code:
#!/usr/local/bin/bash

function ZEROTEST {
        if [ "$ARG1" = "0" ]
         then
          echo -n "Enter valid value: " ; read NEWVAL
         ARG1="$NEWVAL"
        fi
}

for ARG1 in `cat file.txt`
 do
  ZEROTEST
  echo "Value : $ARG1"
 done

Output where I entered 555 as a new value:
Value : 30
Value : 20
Value : 50
Enter valid value: 555
Value : 555
Value : 100
Value : 85


Unfortunately I need this to work somehow in the while loop.

Any ideas why this is and any possible other solutions I should consider?

Thanks
 
The for loop has no input redirection but the while loop does.
You may consider this:
read NEWVAL < /dev/tty

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thanks PHV !! :)

You're a lifesaver ... it's working 100%

That'll teach me hehe... I saw somthing similar in another thread that I tried where it suggested the use of < /dev/null which I tried without joy.

LOL - It's quite obvious to me now why that never worked :)

Cheers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top