kdmurray.blog

The crossroads of life and tech

Running Shell Scripts from the Finder in OS X

Bad AppleOne 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).

Mac Tip: Showing All File Extensions

Finder Preferences in OS XOK, for many of you out there, this is probably so basic you didn’t even need to search for it.  That said, I figured I’d post it anyway (partly because I’ve been so lax about blogging recently).

If you’ve ever wanted to have OS X show file extensions for all files, all the time, it’s a very simple process.

  1. Click on any finder (or the desktop)
  2. Select Preferences from the Finder menu
  3. Click on the Advanced button
  4. Check off the Show all file extensions box
  5. Close the Finder Preferences window

Voila! All is revealed.  Wasn’t that easy?  It probably took you longer to read this than to actually make the change. :)