Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a problem with execution of a while loop, I have found out that the problem involves the execution of the set command, the assigment of the \n character to an environmental variable constitutes a problem. Why does it happen and how to solve it?

my code is:

echo "Enter a filename:\c"
read fname
terminal=`tty`
exec < $fname
nol=0   
now=0       
while read line
do      
    nol=`expr $nol + 1`
    set $line
    now=`expr $now + $#`
done
echo "Number of lines:$nol"
echo "Number of words:$now"
exec < $terminal

When it encounters a line with nothing but a newline character in it, it prints system data and all of the variables:

CINNAMON_VERSION='1.8.8'
COLORTERM='gnome-terminal'
(...)
fname='drunk'
line=''
nol='19'
now='137'
terminal='/dev/pts/0'

(...) indicates omission of an entire block of system data

share|improve this question
    
Use set -- $line –  edwin Aug 2 '13 at 4:59
    
@edwin: Thanks, it works :) Can you please explain, how does it work? How does "--" change the way set processes the input? –  denuviel Aug 2 '13 at 5:41
    
The -- tells set that what follows are the positional parameters. Read help set. –  edwin Aug 2 '13 at 16:22
    
Ok, thanks a lot, I don't know what idea did I have behind asking about a general parameter, instead of reading up on the command. –  denuviel Aug 2 '13 at 19:16

1 Answer 1

up vote 0 down vote accepted

Instead of

set $line

use

set -- $line

Read help set to see why this works.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.