MacOS Finder FAQ: Is there a way that I can execute a custom Unix shell script from the Mac Finder?
Solution: If you ever want to create a Unix shell script that you can give to someone else so they can double-click it and run it through the Mac OS X Finder, all you have to do is (a) name the file with the .command extension and (b) make it executable.
For example, just name your Mac/Unix script like this:
Then make it executable, such as by running
chmod from the MacOS Terminal:
chmod +x ShowProcesses.command
You can also leave out the usual
#!/bin/sh part on the first line.
Now, when someone double-clicks your script in the Mac Finder, the script will open a new Mac Terminal window, and then run the script inside that window. When it’s finished, the Terminal will display a “Process Completed” message, and the user can close the Terminal.
I did this recently for one of my sisters. She has an HP printer attached to her Mac, and from time to time the printer goes nuts and decides to eat the CPU. I run a
top command in a script so she can confirm that this is the problem.
As a simple example of this, create a file named Test.command somewhere on your Mac OS X filesystem, such as the Desktop, or a temp folder somewhere. Put some simple commands in the file, like this:
ls -al pwd
Then make the script executable:
chmod +x Test.command
Now go to the Finder, navigate to the directory where this script is located, and double-click the icon for this file. You should see a Terminal window open, with the output from the commands shown in the Terminal window.
How to determine the current directory
If you need to get the full path of the directory where your script was run from, use this command:
After that line executes, the variable
DIRNAME will contain the full path to the directory where the user executed your script in the Finder. (The
pwd command will just list the user’s home directory.)
In summary, if you wanted to see how to run/execute a Unix shell script from the MacOS Finder, I hope these examples are helpful.