up vote 2 down vote favorite
share [g+] share [fb]

In one of my bash scripts, I am creating a file by repeatedly using echo with output redirection to append to the file. The resulting file, however, is not named properly, but always has an unprintable ^M character appended to the end. Does anyone know what I'm doing wrong? The following simple script demonstrates the problem:

#!/bin/bash
# Should create 'concat.txt' instead creates 'concat.txt^M'
outfile="concat.txt"
echo "'"$outfile"'"
for item in "Able" "Baker" "Charlie"; do
    echo $item >> $outfile
done

System: Ubuntu 9.04 (x64)

link|improve this question

80% accept rate
feedback

2 Answers

up vote 8 down vote accepted

I would suspect that you edited the file somewhere that added DOS-style line endings. Run your file through dos2unix to get rid of them.

dos2unix yourscriptfile
link|improve this answer
feedback

^M is what you would see at the end of every line if you set the line ending to unix mode when the file was written initially in dos mode where the line endings are \r\n

So, while you see

echo $item >> $outfile

unix sees:

echo $item >> $outfile^M

First,

:set ff=unix

Then:

:%s/\r//

to remove the ^M

EDIT

For some silly reason I assumed you're using vim. Maybe because it's the only editor that I've seen show the \r as ^M. Anyway, do what Dennis Williamson said, use the dos2unix tool.

link|improve this answer
That's vi? – Dennis Williamson Sep 10 '09 at 23:29
oh sorry, for some silly reason I assumed he's using vi – hasen j Sep 10 '09 at 23:31
feedback

Your Answer

 
or
required, but never shown

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