One of the things that drives me insane about the Mac on occasion is the ability of OS X to make some of the simplest “power-user” tasks very difficult. Case in point – the ability to execute a shell script from a finder window (or by extension, the desktop).
In most sane operating systems, including Linux and Windows, if you double-click on an executable file, it executes. It’s just that simple. If you create a batch file on Windows (anything ending in .bat or .cmd), the operating system treats that file type as executable and will try to run the contents as command-line commands. In Linux, an operating system which is similar under the hood to OS X, you need to set the “executable” bit in the permissions. This is certainly more of a super-user type task than simply renaming the file, but still quite simple — and consistent across the POSIX world… except for Apple.
chmod +x myscript.sh
So the question is, how do I do this on my Mac? The answer I’ve been given by several people until today was that you would need to use AppleScript or Automator (or Xcode) to create a program that could be run from the Mac GUI. As ludicrous as it seemed, Apple’s tendency to force users to do things the “Apple way” made that quite believable. However I found a post today on Adam Young’s blog from back in 2008 which showed that it is, in fact, possible to do this — it’s just a bit harder than on any other OS. Essentially you have to do both the Linux (chmod) step, and the Windows (specific file extension) step.
mv myscript.sh myscript.command
chmod +x myscript.command
You need to use the .command extension for the Finder to actually attempt to run your shell script. An identical file with the execute bit set but with a .sh extension will simply open up in Xcode (or whatever editor you have set for .sh files).