In case anyone’s curious here’s an abbreviated version of the story typed mostly from memory:
ASCII is the standard for Latin character encoding in North America. It was originally designed to control teletype machines. Teletype machines are basically typewriters, but where the keyboard and the ‘typewriter part’ are separate devices connected by a telegraph line and potentially in different cities or wherever.
In order to control a typewriter remotely, ASCII needed codes not just for all the characters it could produce, but also all the other functions a typewriter could perform, as well as a few additional transmission-related messages. Such codes are referred to as ‘control characters’.
When you’re using a typewriter and you run out of room on a line and hit the return key, the typewriter actually does 2 distinct things:
- It moves the carriage back to the leftmost position (a ‘carriage return’).
- It moves the paper down one line (a ‘line feed’).
Because these are different functions actuated by different mechanisms, each got its own ASCII character. That’s what \r
and \n
are — \r
is the ‘carriage return’ character and \n
is the ‘line feed’ character. Thus in the original application of ASCII every line ended with \r\n
.
Then computers came along, and the companies designing them generally decided to use ASCII to encode their text, because it was an existing and relatively simple standard. But, there was the question of what to do about line endings.
Microsoft looked at \r\n
line endings and said “well, that’s the existing standard, we might as well stick to it”. So DOS and Windows use \r\n
line endings.
Early Unix developers looked at \r\n
line endings and said “that’s stupid, we don’t need two characters at the end of every line, let’s just use \n
instead”. So UNIX, Linux, and all the systems based on it use \n
line endings.
Apple looked at \r\n
line endings and said “that’s stupid, we don’t need two characters at the end of every line, let’s just use \r
instead”. So classic Mac OS used \r
line endings.
(Note that Mac OS X threw out all the classic Mac OS code and started from scratch with Unix-y underpinnings, so modern macOS uses \n
line endings. Nothing really uses only \r
any more.)
This mostly worked fine until the internet made it much more common to need to open files created on other types of computers. Opening and parsing files with line endings different than those native to your system can create all sorts of interesting problems.
Today’s text editors and other programs are mostly smart enough to figure out what line ending type is being used and convert as necessary to avoid problems without bothering the user about it. But, it’s not uncommon to encounter line-ending-related problems when doing stuff on the command line.