Thursday, November 15, 2012

Removing ^M characters in bash scripts for Mac OS X

When your bash script you copied from unix/linux to your windows machine and then copied it to Mac doesn't work, and you see an error like this:

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

probably because your source code contains annoying Control+M (^M) characters when saved in a Windows machine. There are two (2) ways to remove this.

1. Create a bash script dos2unix.sh in Mac terminal 
1.1 Using vi, create the file below
   #!/bin/bash
   file=S1
   cat $1 | col -b > temp
   mv temp $1
   chmod a+x $1


1.2 Make the script executable 
      $ chmod a+x dos2unix.sh
1.3 Execute the script
     $ ./dos2unix.sh myshellscript.sh


2. Rremove the ^M in Mac using tr. 
   2.1. First view the file using
         $ cat -e unixScript.sh 
         $ od -tc unixScript.sh
  2.2. Remove using the command below
         $ tr -d '\r' < unixScript.sh > macScript.sh