This is, in general, not possible for an actual script.
A standalone executable script will have a shebang line that identifies the interpreter to use:
#!/bin/sh
The problem is that, regardless of the interpreter, the shebang line itself will contain a carriage return character before the end, meaning that the interpreter won't be found (barring the unlikely executable name of literally $'sh\r'
- which I think is illegal on Windows).
The other kind of executable script is a plain text file with the execute bit set, which POSIX requires to be interpreted as a script in the POSIX shell command language (when invoked from a compliant shell itself). This shell language, however, as you've found, treats carriage returns as data bytes, so you have the issue you've identified.
You have some options. One is to forego an actual executable script directly, and simply to invoke an interpreter for some other language first. You've identified Perl and Python, and in fact most scripting languages are happy with any contemporary line-ending format. Invoking the script as perl cleanup.pl
will not be a problem.
Many administrative tasks are much easier in a conventional shell language, however, and there is one more trick: end every line with a comment.
echo hello #
rm file.ext #
mv /path/other.fl /path/bin #
The #
character introduces a comment to the end of the line in all standard shells (in non-interactive contexts). The comment will include the carriage return byte, which is a fine element of a comment, and then end immediately afterwards with the terminating line feed byte.
It's important that there be that space before the hash: a #
inside a word does not begin a comment, but is part of the word.
You could run this script directly with a shell:
bash cleanup.sh
dash cleanup.sh
sh cleanup.sh
But if you're going to launch it by typing a command from an existing shell session, those POSIX scripts mentioned earlier will also work: just make the file executable, and then
./cleanup.sh
will run it using whatever your shell considers the right thing to do for a POSIX script.
Since this sounds like a one-off it probably isn't worth the effort of making it executable, so just sh cleanup.sh
seems adequate to me.
My honest suggestion for this situation is probably Powershell (or batch at a push), but I understand it's not what you want. WSL is another option: it handles carriage returns in the shebang line automatically, and then you can use comments for the rest.
dos2unix
or plain oldsed
? – Rui F Ribeiro Dec 31 '18 at 04:54python
andperl
that are line-ending insensitive. – Greg Nisbet Dec 31 '18 at 04:58bash
itself can't be configured to process\r
differently. – Greg Nisbet Dec 31 '18 at 05:25