0

I am hoping someone can explain the following result I am receiving with my simple script. I cannot understand why only the last variable being echoed comes out properly.

#/bin/bash
MYFILE=$1
while IFS= read -r line || [ -n "$line"]
do
    echo "Ref will be ${line}.txt and label is ${line}"
done < $1

After I run it:

$ ./myscript.sh myfile.txt
 .txt and label is KAT1
 .txt and label is KAT2
 Ref will be KAT3.txt and label is KAT3

Why are the all the lines before the last line only half being processed properly???

CuriousDude
  • 1,087
  • 1
  • 8
  • 21
  • I don't think that what I asked is a duplicate of that - I am having an issue with how my results are showing, not an issue with errors because of carriage returns. Mine appears to be an actual issue with bash itself so I am wondering if editing my script in anyway will even solve this. – CuriousDude Oct 25 '19 at 17:55
  • I think he is saying there are carriage returns in your file and not the script. Carriage returns can have some strange affects on the terminal. Send your output to a file and open it in vim, and you will see the difference. `./myscript.sh myfile.txt > out.txt` – Jason Oct 25 '19 at 18:05
  • There aren't any I have written the script in vim and have set ff=unix. I did get those errors before but had solved it that way. Now it is running but the actual output in my terminal is wonky.. – CuriousDude Oct 25 '19 at 18:06
  • 1
    no no.. There are carriage returns in myfile.txt. Not the script. – Jason Oct 25 '19 at 18:07
  • 1
    Some terminals will use a carriage return to just put the cursor at the beginning of the current line. When it does that, you begin over-writing the original text. This won't happen if you route the output to a different file and open it in an editor. – Jason Oct 25 '19 at 18:08
  • Ohh okay I had misunderstood that. Yes you are right - wow did not realize this issue was also in simple text files with just 3 lines in it. That's so strange! Thank you though this solved it I was so worried it was going to be a lot more complicated! – CuriousDude Oct 25 '19 at 18:09
  • Add `sed -i 's/\r//g' "$1"` to filter the carriage returns out of the file. Or if you just want to filter them out of the loop and leave the file untouched, you can change the input to the loop like this `done <<< "$(sed 's/\r//g' "$1")"`. By the way, do not forget to quote your variables. A file name with spaces would break your script. – Jason Oct 25 '19 at 18:14

0 Answers0