Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - seamlessly run scripts with CRLF line endings

I am using VM (in my case simply boot2docker) to run docker containers on Windows host. For convinience, my source files are mapped from host file system, so text files are by default using Windows-style CRLF line endings instead of Unix-style LF endings.

When I try to run some .sh file from docker container, I'll get an error

bash: ./script.sh: /bin/bash^M: bad interpreter: No such file or directory

Is there a way how could I somehow tell bash/sh interpreter to automatically convert \r\n to \n and run a file?

Sure, I could do some piplelining like this cat script.sh | tr -d "\r" | sh or even create an alias for that, but it would not cover situation where one script includes another.

The only acceptable solution I have found so far, is to set Git to checkout source files in UNIX format.

like image 670
trebi Avatar asked Apr 13 '15 11:04

trebi


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 can I tell if a file is CRLF or LF?

use a text editor like notepad++ that can help you with understanding the line ends. It will show you the line end formats used as either Unix(LF) or Macintosh(CR) or Windows(CR LF) on the task bar of the tool. you can also go to View->Show Symbol->Show End Of Line to display the line ends as LF/ CR LF/CR.

What is CRLF in Linux?

The characters CRLF are often used to represent the carriage return and linefeed sequence that ends lines on Windows text files. Those who like to gaze at octal dumps will spot the \r \n. Linux text files, by comparison, end with just linefeeds.


1 Answers

You can commit a .gitattributes file in your repo in the root folder to automatically tell Git to apply LF line endings to all .sh files when checking out, even on Windows. This way you or other developers don't have to remember to configure Git on each machine where you clone your repo.

# Set line endings to LF, even on Windows. Otherwise, execution within Docker fails.
# See https://help.github.com/articles/dealing-with-line-endings/
*.sh text eol=lf
like image 129
Christoph Avatar answered Oct 08 '22 18:10

Christoph