Bash – Carriage return issue

bashnewlinesshell

I have this in a bash script

DAY2="20130605"<Cr>
echo  "This is yesterday date:"$DAY2"end"

Why is the output the following? It seems as though there is a carriage return in DAY2 but where is it coming from?

ends is yesterday date:20130605

Best Answer

Carriage return puts the cursor back to the beginning of the line. Your output string is:

    This is yesterday date:20130605<Cr>end

Except, when the terminal hits the <Cr> it returns the cursor to the beginning of the line and overwrites the characters that are there.

In other words, "Thi" gets replaced with "end", producing:

    ends is yesterday date:20130605

To do what you appear to be trying to do your script should look something like this:

   variable="text"
   echo "Some sentence $variable"

Which will output

   Some sentence text

IF there are stray carriage returns they should show up as ^M in vi (as Bruce said)

Solution 1

The best way to remove carriage returns or other non-printing characters is with the tr command with the -d option, which deletes any instance of a single character, with \r which is the escape sequence for carriage return:

    tr -d '\r'

This will remove all carriage returns. Run it on the script to remove all instances of carriage returns, then overwrite the original script file:

    tr -d '\r' yourscript.bash > temp
    mv temp yourscript.bash

Solution 2

or while in vi with the script open enter:

    :%s/\r//g
    :wq

To remove the carriage returns within the document then save it.

Related Question