Twice Foiled by CRLF on Linux

I’m just going to get this off my chest.  There is no reason in the world why life has to be this difficult.  These computers were brought into our lives to easy the pain and yet, somehow, they just don’t measure up!  I have been bitten by this one twice.  It’s clearly evident had I blogged about it before now, I could have reclaimed a day of my life back.

So Git has this thing with carriage return/line feed characters and it should all make our lives easier when transitioning between a Linux environment and a Windows environment with our code.  I had given it a cursory look a while back and configured my own machine to, once and for all, prevent the mayhem that arises out of saving files with CRLF (Carriage Return Line Feed) characters onto a Linux Server.  Well, I forgot about it, and it took me nearly a day to figure out why I couldn’t run a simple bash script that calls a simple PHP page that processes a simple set of commands that ultimately is configured for a simple cron job to run every single day.

SYNOPSIS:  When on a Linux server, you cannot run a bash script if that script ends in an CRLF.  It fails miserably.  In my case my script file called:

php /do_important_things.php

The error returned (from having a CRLF at the end) was:

Could not open input file: /do_important_things.php

When you’re walking into an error that says: “Could not open input file”,  and you have no idea why it doesn’t work,  I can guarantee you, CRLF, is not the first thing that pops in your head.  In both instances, this stackoverflow question and answer by chown has proven invaluable to me!

I have since adapted the Git Repository to include a .gitattributes file (as recommended) that states the handling conditions of the line endings.  So this shouldn’t ever happen again…on this repository.

# Set default behavior, in case users don't have core.autocrlf set
* text=auto

# Explicitly declare text files we want to always be normalized and converted
# to native line endings on checkout.
*.c text
*.h text

# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary