Wednesday, February 18, 2009

: bad interprer: No such file or command

Hello and welcome to this weeks edition of practical shell scripting. This is one for the newbies and cross platform folks. If you've ever worked in cross platform development environment you know there are several obstacles that you will encounter with issues like directory paths and permissions. But one of the sneakiest of these obstacles is the that Unix does not recognize carriage returns characters. In fact they will really fowl things up, and this can occur from a couple of different sources. I'll give you some examples of these in a few moments, but first let me lay out situation that I always encounter.

I write some script to do some arbitrary thing and test it to make sure it works. Then I check it into our revision control system. Then a few weeks later someone else edits the file and checks it back and then it suddenly doesn't work. When you try to execute it you get

:bad interprter : No such file.

How can this be, you're looking right at the file and still it won't execute. Here's what happened,
the last person to edit the file did so using a windows based editor ( like word pad ) and that editor placed a carriage return at the end o each line in the script. If you cat the file or vi the file it looks fine and yet it gives you this error. Here's how to fix it, view the file using `cat -t`, it will show you the hidden characters. These carriage returns look like ^M at the end of each line. There's a couple of fixes for this. On more current unix distributions there is a utility called dos2unix which will strip the ^M out of the file, however on the older Unix's you can do a sed command like this:

sed 's/^M//g' FileThatsMessedUp.sh > FileThatsFixed.sh

The trick is that the ^M is created by pressing the Ctrl button at the same time as the letter v, and then Ctrl and the letter m. Now view your FileThatsFixed.sh using he cat -t command and look for the ^M's. They should be gone.

One other sneaky part of this is is that once this happens the FileThatsFixed.sh will no longer have execute permissions, so you'll need to go back and set those to executable. I'm not sure if this will survive porting to html, but I'll give it a go and see what happens.

FileThatsMessedUp.sh

#!/bin/bash

echo "foo"
echo "foo"
echo "Just testing"


FileThatsFixed.sh

#!/bin/bash

echo "foo"
echo "foo"
echo "Just testing"


If these don't work for you, just copy a file onto your windows box and open it up with notepad or word pad and give it a try.

That's it for this weeks.