Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


while read line; do 
echo $line 
done < $FILE

I am new to bash scripting and trying to figure out this while loop. I want to read line by line from a text file and then do a command.

I keep getting the error:

 No such file or directory121/bin/list.txt

Does anybody know how to fix this?

share|improve this question
Have you tried adding a second echo after the first? echo $line; echo. It won't solve your problem, but it might allow you to see the full error message. I don't see anything obviously wrong with your script, other than possibly the file name. – Michael Kjörling Jul 1 '13 at 14:13
What happens if you replace the shebang line with #!/bin/bash -x ? (-x and -v enable extra debugging information). – Hennes Jul 1 '13 at 15:53
up vote 3 down vote accepted

I suspect your script may have DOS-style line endings. In DOS (and Windows), each line of a text file ends with carriage return (variously represented as \r or ^M) followed by a linefeed (\n or ^J). Unix text files, on the other hand, end each line with just a linefeed. If you give a unix tool (like bash) a DOS-formatted file, it'll interpret the carriage return as part of the line, and get quite confused. In this case, it looks to me like FILE is actually getting set to /u0146121/bin/list.txt^M, which doesn't exist, and when the shell reports the problem the carriage return confuses the terminal and the end of the error message gets printed over top of the beginning.

To check, try printing your script with cat -v /path/to/script -- if you see ^M at the end of lines, you have a DOS-format file. Your system probably has a command to translate it, but the command name varies (e.g. it might be dos2unix or fromdos or ...). If you can't find a relevant command, you can use this trivial perl script:

perl -pi -e 's/\r//g' /path/to/script
share|improve this answer
you are right it does have a ^M. – mkrouse Jul 1 '13 at 17:12

You are probably not showing us exactly what you are doing. The error message is

No such file or directory121/bin/list.txt

which shows that $FILE contains 121/bin/list.txt instead of /u0146121/bin/list.txt so I can only guess that you are not actually running FILE="/u0146121/bin/list.txt" but FILE="121/bin/list.txt".

In any case, try running it without defining a variable to see if it works:

while read line; do 
  echo $line;
done < /u0146121/bin/list.txt
share|improve this answer


while read line; do 
echo $line 
done < cat $FILE
share|improve this answer
This isn't any different, except it's a Useless Use of cat. – slhck Jul 2 '13 at 13:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .