while read loop; scope of variables (shell)


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting while read loop; scope of variables (shell)
# 1  
Old 03-03-2009
while read loop; scope of variables (shell)

If I set a variable within a while-read loop, sometimes it's local to the loop, sometimes it's global, depending on how the loop is set up. I'm testing this on a Debian Lenny system using both bash and dash with the same results.

For example:
Code:
# Pipe command into while-read loop

count=
ls -1 | while read line; do
    count=$((count + 1))
done
echo "Count = $count"

In this case, $count is null outside the loop.
The loop set up a separate variable named count and ignored the global variable named count.

Note: Yes, there are better ways to count files in a directory.

So let's try this:
Code:
# Redirect file into read-while loop

ls -1 > /tmp/junk
while read line; do
    count=$((count + 1))
done < /tmp/junk
rm /tmp/junk
echo "Count = $count"

That works as expected.
We didn't even need to declare count as a global.

Let's try to avoid the temp file by using a Here Doc.
Code:
# Redirect Here Document into read-while loop

while read line; do
    count=$((count + 1))
done << EOF
$(ls -1)
EOF
echo "Count = $count"

This also works as expected.

The example using the pipe did not work.
My guess is that the pipe somehow launches a child process or subshell or something like that, and variables created within a child are not visible to the parent.
Ok, I can live with that. I think it even says so in the man pages.

But, another thing I noticed is the variable "line" used in all three examples is never visible outside the loop. This would imply a child process as well. Or maybe not?
This is where I am confused.
Why is "line" always invisible outside the loop, but "count" is visible, provided we don't use a pipe?

-MD
# 2  
Old 03-03-2009
With something like:
A=""
echo test | read A
echo A

You have a problem because the "read" statement is executed in a subprocess with almost every shell. The only exception I know is the real Korn shell. The Korn shell will execute the last command of a pipeline in the current shell if it is a korn shell builtin. This does not apply to pdksh, only the real Korn shell. Your "while" statement is just a compound command.

But a loop like:
while read line ; do some-command ; done
runs until the "read line" get no input. This changes the value of line to nothing. So even if the loop is running in the current shell, line will be empty when the loop exits.
# 3  
Old 03-03-2009
Ah! (light bulb turns on inside head)
I get it now.
I was thinking the "line" variable would hold the last line read.

so with:
while read line ; do some-command ; done < some-file

"read" tries to read the next line after the end of file, which is null,
and sets "line" to null, and returns "false" so the loop will end.

The "line" variable is not "invisible" outside the loop,
it just looks like that because it ends up null.

Just to make sure,
Code:
while [ "$line" != "Fred" ]; do
    read line
done << EOF
Wilma
Barney
Fred
Betty
EOF

echo "Line = $line"

The result is "Fred" in both bash and dash.

I've used this method before, but never really understood how it worked.

Thanks.

-MD
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Unable to read assign values to two variables in while loop

I am trying to read a input file which has two columns separated by space Input file server1 server2 server3 server4 server5 server6 When i execute the below while code it reads line by line and a and b variables are able to successfully fetch the values while read a b do echo "$a" echo... (5 Replies)
Discussion started by: chidori
5 Replies

2. Shell Programming and Scripting

The scope of the shell/perl script is to read the input text file. Validate the expiry date of each

The scope of the shell/perl script is to read the input text file. Validate the expiry date of each certificate and send the mail to the user. The user takes action to add the new certificate to the storage file and user owns the responsibility to update the input text file with the new certificate... (5 Replies)
Discussion started by: casmo
5 Replies

3. Shell Programming and Scripting

Bourne Shell - Problem with while loop variable scope.

Hello I am having issues with a script I'm working on developing on a Solaris machine. The script is intended to find out how many times a particular user (by given userid) has logged into the local system for more than one hour today. Here is my while loop: last $user | grep -v 'sshd'... (7 Replies)
Discussion started by: DaveRich
7 Replies

4. Shell Programming and Scripting

Scope of variables between scripts

Friends, I am using ksh under SunoS. This is what I have In file1.sh NOW=$(date +"%b-%d-%y") LOGFILE="./log-$NOW.log" I will be using this file through file1.sh as log file. I have another script file2.sh which is being called inside my file1.sh. I would like to use the same log... (6 Replies)
Discussion started by: dahlia84
6 Replies

5. UNIX for Dummies Questions & Answers

For loop control with two variables in csh shell

Hi All How can i control for loop with two different variables in csh shell Regards Nikhil (1 Reply)
Discussion started by: Nikhilindurkar
1 Replies

6. Shell Programming and Scripting

Variables scope.

Hi , I'm trying to change the variable value in a while loop , however its not working it seems that the problem with subshells while reading the file. #!/bin/sh FLAG=0; cat filename | while read data do FLAG=1; done echo $FLAG Should display 1 instead displays 0 (13 Replies)
Discussion started by: dinjo_jo
13 Replies

7. Shell Programming and Scripting

Doubt about variables scope

I call my script with two parameters myscript.sh aaa bbb What is the way to access $1 and $2 values inside a function? I call the function like this myfuntion $1 $1 but inside of the function, $1 and $2 are empty. Any suggestions? thank you in advanced. (1 Reply)
Discussion started by: aristegui
1 Replies

8. Shell Programming and Scripting

Doubt??? [scope of variables]

Heres an example..... <~/abc>$ cat textfile line 1 line 2 line 3 line 4 line 5 <~/abc>$ cat try.sh #/bin/ksh for runs in 1 2 3 do A=$runs echo "Inside A : $A" done echo "Outside A : $A" <- works fine (1 Reply)
Discussion started by: qzv2jm
1 Replies

9. Shell Programming and Scripting

Access Awk Variables Outside Scope

My awk script searches for specified patterns in a text file and stores these values into mem variables. Once this is done I want to Insert these values into a table. How can I avail of the variable values outside the scope of awk script.... One method that I have tried is to write the... (7 Replies)
Discussion started by: Amruta Pitkar
7 Replies

10. UNIX for Advanced & Expert Users

Access Awk Variables Outside Scope

Sorry in the wrong forum. Moving this to right forum. (2 Replies)
Discussion started by: Amruta Pitkar
2 Replies
Login or Register to Ask a Question