Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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)

share|improve this question

2 Answers 2

up vote 11 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
share|improve this answer
    
To check for Windows line-endings, run cat -vt file.ext and look for ^M's. –  ken Jun 8 at 5:58

^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.

share|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 –  hasenj Sep 10 '09 at 23:31

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.