Problem with read line

Hi everybody, I am new to shell script. Please help me with this problem.
I have a file test.txt with the content like this:

I have a shell script test.sh like this

#!/bin/sh 

while read line
do    
    echo $line >> out.txt
done < test.txt

out.txt is expected to have the same content with test.txt. But here is the output.txt

laconfirm remote1 test.sh test.txt are files in the same folder.
It replaces the * in the original text.txt

Would you please tell me what is my problem and how I can fix it?
Thanks in advance.

echo "$line"

the best way to make an exact reproduction is like this:

while IFS= read -r line
do 
  printf "%s\n" "$line"
done < infile > out.txt
1 Like

You save me! Many thanks :slight_smile:

Wouldn't your code add an empty line at the end of the out.txt even if infile doesn't have one ?

Good question. No it would not add an empty line. An empty line would mean 2 consecutive linefeed characters. Or do you mean add a linefeed character if it isn't there? If a file does not have a linefeed at the last line then it isn't terminated and that line would then not be read by the read statement.

1 Like

yes i meant that ...

Ah ok, thanks a lot for the explanations, i will sleep a bit less ignorant tonight ;)...

Without quote

echo "$line"

Why does it read all files in that directories?
Or why does it print those extra lines without quote?

It is because the * gets interpreted and expanded by the shell to the content of the current directory. Just go into a directory and issue:

var=*
echo $var

If you put quotes around $var, you just get the asterisk

2 Likes

Pin point answer.
Thank you.

Hi, another question.
Is there any posibility that this error only happens in some versions of the operation system?
I received that script from a friend of mine, and he said that there were no such error in his computer. I am using Ubuntu 10, and he is using Ubuntu 9.

No not really. What could have happened is that his input files simply did not have asterisks in them. It could also be that he set globbing to off (i.e. no asterisk expansion) in his shell (not very likely) It could also be that he always executed the script from an empty directory, in which case the asterisk would also not get expanded. To illustrate:

$ mkdir test
$ cd test
$ echo *
*
1 Like