Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure bash to handle CRLF shell scripts?

I want to execute bash scripts that happen to use Windows/CRLF line endings.

I know of the tofrodos package, and how to fromdos files, but if possible, I'd like to run them without any modification.

Is there an environment variable that will force bash to handle CRLF?

like image 438
mcandre Avatar asked Jan 30 '13 17:01

mcandre


People also ask

What is CRLF bash?

Trivial as it is, it has \r\n (that is, CRLF, that is carriage return+line feed) as line endings.

How do I move a carriage return in bash?

To output a carriage return, instead of echo "/n" , you need to do printf "\n" , with a backslash and not a slash, or even better just echo without arguments.

Does CRLF work in Linux?

Linux applications and applications libraries mostly handle all types of newlines including CRLF (MS-DOS, Windows) or LF (Unix, Linux) seamlessly. You don't need to change or specify anything.


2 Answers

Perhaps like this?

dos2unix < script.sh|bash -s

EDIT: As pointed out in the comments this is the better option, since it allows the script to read from stdin by running dos2unix and not bash in a subshell:

bash <(dos2unix < script.sh)
like image 140
Magnus Gustavsson Avatar answered Oct 06 '22 00:10

Magnus Gustavsson


Here's a transparent workaround for you:

cat > $'/bin/bash\r' << "EOF"
#!/bin/bash
script=$1
shift
exec bash <(tr -d '\r' < "$script") "$@"
EOF

This gets rid of the problem once and for all by allowing you to execute all your system's Windows CRLF scripts as if they used UNIX eol (with ./yourscript), rather than having to specify it for each particular invocation. (beware though: bash yourscript or source yourscript will still fail).

It works because DOS style files, from a UNIX point of view, specify the interpretter as "/bin/bash^M". We override that file to strip the carriage returns from the script and run actual bash on the result.

You can do the same for different interpretters like /bin/sh if you want.

like image 42
that other guy Avatar answered Oct 05 '22 23:10

that other guy