Pressing enter produces ^M instead of a newline

In case anybody else has this problem, it is most likely a problem with the stty terminal line setting rather than a TERM problem. If this happens to you again, try running stty sane and let us know if that fixes it.


Try running stty -a to view your terminal settings. My suspicion is that your icrnl setting is not set and will be shown as -icrnl (the minus sign means that it is turned off) instead of having its usual setting of being on. Here is how my terminal is normally set up when I log in:

$ stty -a
speed 38400 baud; rows 45; columns 80; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl -ixon -ixoff
-iuclc -ixany -imaxbel iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke

And I have no problem with line endings: either return (^M) or enter (^J) will end input lines. But if I turn icrnl off then ^M codes suddenly appear each time I am talking to a program and hit enter:

$ stty -icrnl
$ read line
Line of text^M^M^M^M
$ stty -a
speed 38400 baud; rows 45; columns 80; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff
-iuclc -ixany -imaxbel iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke

The code icrnl means “turn carriage returns into newlines” and hides from the running program that you might be typing ^M when Unix really wants ^J. Old keyboards used to have a separate Return and Enter key (where Return typically advanced you through a form and Enter submitted it), but today we generally have only one line-ending key and so this terminal setting helps combine the two meanings.

Add the stty icrnl command to your .profile or .bashrc if you find that this is indeed the problem setting.