brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: tr -d '\r' strips Windows line endings from a file

Linux
~/tips/tip-shell-tr-delete-carriage-return

cat -E script.sh | head

Removes the hidden carriage returns that make Windows text files misbehave on Linux.

A shell script written on Windows can look perfect in an editor and still refuse to run on Linux. The usual culprit is invisible: Windows ends every line with a carriage return plus a newline, and bash sees that extra \r as part of your commands.

First, check whether that’s really the problem. cat -E marks the end of every line with a $, and a carriage return shows up as ^M right before it:

cat -E script.sh | head

If you see ^M$ at the end of the lines, tr can delete every carriage return in one pass:

tr -d '\r' < script.sh > script-fixed.sh

-d means delete the characters in the set, and '\r' is tr’s escape for the return character. Then check the new file with cat -E again, make it executable and swap it in. The same fix works for a CSV exported from a spreadsheet on Windows, where the stray return otherwise ends up glued to the last value of every row and breaks comparisons later on.

Two things to watch. tr only reads standard input, so you can’t give it the file name as an argument; that’s why the command uses < and >. And don’t redirect into the file you’re reading from, because the shell empties it before tr starts. Write to a new file and move it over. Also, -d '\r' removes every carriage return in the file, not only the ones at line ends. In a normal text file that’s exactly what you want. In a binary file it would break things, so only use it on text.

Further reading: tr(1) manual page, cat(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link