Industry guru Dave Taylor offers tech support on technical and business topics, including iPhone, iPod, Microsoft Windows, Sony PSP, cellphones, online advertising, CSS, Web design, business, Unix, Linux, SEO, Mac OS X, and shell script programming.     


How do I create a shell script on a Macintosh?

A reader writes:
I've started to go through your shell script book Wicked Cool Shell Scripts but there is still something I'm unclear on. I'm showing my ignorance here, but how exactly do you save a shell script so you can use it later?"

Dave's Answer:
If you're comfortable using the vi editor within the Mac OS X environment, your best bet is to open up a Terminal window (Applications -> Utilities -> Terminal) and type in the script directly.

If not, you can use an application like BBEdit, save the file as text-only with or without line breaks, then open up the Terminal application and type in the name of the script, as in sh myscript.sh (assuming you saved the file as 'myscript.sh').

The final step is for you to actually make the script executable, which you can do by using the chmod command, as in: chmod +x myscript.sh.

Once you've done that - particularly if you have the script in one of the directories in your PATH - you can execute the script by simply typing its name at the command line.


Related Shell Script Programming articles:
✔   Secretly capture screenshots on my Mac?
When I used to work on a Linux system, there was a utility we had that would let me take screen captures every...
✔   Parsing "id" strings in a Shell Script?
Hello Dave. I need a Bash shell script that creates a directories with the group names automatically when user logs in to the...
✔   Copy and Paste from the Mac OS X Command Line?
I am constantly running commands in Terminal.app on my MacBook and then copying and pasting the results into email messages or documents. Yes,...
✔   Script to test line lengths for Twitter compatibility?
I've been tasked with writing a series of tweets for a Black Friday marketing campaign and am finding it a bit tricky because...
✔   Shell script to convert lowercase to title case?
As part of a project I'm working on, I find myself deep in a Linux shell script, needing to have a subroutine that...

Let's stay in touch!
Sign up for my weekly AskDaveTaylor Newsletter and you'll receive even more tech and gadget help right to your inbox, along with exclusive news and industry updates. It's good stuff. I promise!
    Enter your name: and your email addr:  









Reader Comments To Date: 21

Soheb said, on September 3, 2009 1:55 AM:

Hello,

How can I create one that will delete the file "cache.db" in the directory "Library/Application Support/Shutterbypass" I was hoping there was a way to create a file that i can save to my desktop and just double click on it and this will happen automatically. Like a batch file in Windows.

Thank you,
Soheb V

xapa said, on October 21, 2009 8:22 AM:

Hello,

write this on a text doc and save file as 'remove_cache.sh':

#!/bin/bash
rm /Library/Application Support/Shutterbypass/cache.db
exit

Then select it from Finder and cmd+i to get file info. On 'Open With' go browse and select Terminal.app (/Applications/Utilities).

Then open Terminal.app and write:

chmod +x (and drag from finder the script 'remove_cache.sh')

That's all, when double click the script, it will delete the cache.db.

Salut,
Xapa

sehpamorr said, on December 13, 2009 2:46 PM:

An easier way to execute these scripts is to put them into an applescript. This way, they can be saved as an application that you can add to your dock etc.

To do so:
Open script editor (in the utilities folder in Snow Leopard, in the applescript folder of applications in 1.5 or before)

enter:

do shell script
then contain the contents of your script between two single quotes

ex.
do shell script 'echo hi'

then you can save this file as an application through the save menu

Grant said, on August 9, 2010 7:18 AM:

this maybe a dumb question, do you have to stop ichat server before executing this script?

thanks,

Dave Taylor said, on August 9, 2010 7:53 AM:

Not a dumb question at all, Grant, but I really can't see how running an iChat server would have any impact whatsoever on creating a separate script...

Jeff S. said, on October 20, 2010 11:28 PM:

Hello,

I hope that you are able to assist me.

I am running a WebSTAR server on an old Macintosh G4 500 MHz DP mini-tower running Tiger 10.4.11. One of the websites that I operate requires using PHP and a mySQL database.

While Tiger has PHP 4.4.9, I am using a self-contained version of PHP 5.2.0 which is installed in:

/Applications/PHP5/bin/this is where the actual php binary is located

This is a self-contained PHP package that I downloaded from the Zend website.

The problem is that PHP crashes several times throughout the day. I don't know if it is a result of so many search bots hitting the site, or people who are maliciously attacking the site, or what, but the constant PHP crashing is annoying, and makes the site unreliable.

Currently, the way I have dealt with the PHP crashing problem is by keeping "Activity Monitor" open on my desktop, as well as the Terminal. Whenever I see PHP disappear from "Activity Monitor", I follow the instructions provided by 4D -- the makers of WebSTAR -- and type the following in the Terminal to restart PHP:

set env PHP_FCGI_CHILDREN 8
./fcgirunner.pl xxxx ./php

The x's are the port number.

"fcgirunner.pl" is an old PERL script released by Zeus Technology to startup remote FastCGI processes with their Zeus Web Server.

As you can imagine, it is a hassle to have to keep an eye on PHP, and reboot it manually every time that it crashes, and I do have to sleep. With that in mind, I am interested in finding a way to automatically watch the PHP binary that is located at the above path, and to automatically relaunch the PHP binary in fcgi mode by using the above two Terminal commands, without having to keep "Activity Monitor" and the Terminal open all the time.

In short, I need a solution which will do two things:

1. Keep an eye on the self-contained PHP installation.

2. Automatically reboot the PHP binary in fcgi mode -- as per the above two Terminal commands -- every time that it crashes.

Someone on another site suggested that I use a shell script, but I have basically no experience with such things. They suggested that I begin with something like the following, but to be honest, it is all Greek to me:

=============================

[CODE]
#! /bin/bash

ofPid='/bin/ps -ax | grep php | grep -v pidcheck.sh | grep -v grep'

if [[ -n "$ofPid" ]]
then
exit 0;

else

/Applications/PHP5/bin/fcgirunning.pl
fi
exit 0;
[/CODE]

=============================

Another person suggested that I use "launchd with the KeepAlive key enabled", but I have no idea whatsoever how to do that. They offered this example:

=============================
[CODE]


Label
my.textedit.job
KeepAlive

ProgramArguments

/Applications/TextEdit.app/Contents/MacOS/TextEdit


[/CODE]

=============================

They also pointed me to the launchd manual on the Apple site, and to a page about daemons and agents, but again, it is way over my head.

What would be perfect would be a shell script enclosed in an Applescript -- as you described in a previous comment -- which I could save as an application, and then add to my startup items. That way, the minute I start up the G4, PHP will automatically be launched, and the script will keep an eye on it.

It would be necessary for this script to check the PHP process every minute to make sure that it is still running, as otherwise, if PHP crashes, visitors to the site just get a blank, white page.

Please bear in mind that I am not very proficient at using the Terminal, and have very little experience at writing Applescripts, or any other scripts. So, if you offer that kind of a solution, you will need to provide me with very clear step-by-step instructions.

Thanks so much in advance.

Jeff S. said, on October 20, 2010 11:46 PM:

BTW, the fcgirunner.pl PERL script is located at the same location as the php binary in /Applications/PHP5/bin/.

The script must start fcgirunner.pl, watch port 8081, and start PHP when it crashes.

Leigh said, on November 18, 2010 5:58 PM:

I am using geektool for mac and wrote a script to ping my work server but I want to be able for that script to ping all our servers but display in one shell.

Is it possible? Here is my basic script:


HOST=server name
PING=`ping -q -c 1 $HOST`
if [[ $? -eq 0 ]] ; then
TIME=`echo $PING |tail -1 | cut -d/ -f 5`
echo -n ${TIME}ms away from $HOST
exit 0
else
echo -n $HOST could not be reached
exit 2
fi

feel free to email me leigh.kalbli@me.com

Kiel said, on December 23, 2010 11:23 AM:

Hey, I'm trying to run the todo.sh script (found https://github.com/ginatrapani/todo.txt-cli/wiki/User-Documentation). I can get everything set up, and I run:
sh todo.sh
chmod +x todo.sh

But then, when I try and run todo.sh, I get:
-bash todo.sh: command not found

Do I need to run something else in order to get this to run in a bash shell? Or is there some step I'm forgetting?

Dave Taylor said, on December 23, 2010 5:43 PM:

Kiel, I don't know that script, but generally it sounds like your current directory isn't in your PATH. Try this:

./todo.sh

and see if that works!

Lance Bliss said, on February 25, 2011 11:46 PM:

I am new to the terminal and my work is letting do some work from home.

I am suppose to add some lines in my local host terminal to allow me access my work environment.

I have the lines I am suppose to add below my
127.0.0.1 localhost to allow me access to my work environment.

But I am lost as how to actually insert them into the terminal below the 127... localhost.

How do I add a couple lines of text below the 127. ... localhost ?

I have tried looking on the internet, but to no avail.. I now know how to do lots of other neat commands except how to enter text into my terminal.

Do I have to use the vi thingy or open up a text editor and type it in there and then paste it into the terminal.

Thanks for your help in advance.
The newbie.. :)

Kim said, on February 27, 2011 1:34 PM:

How can I have the best of both worlds?

1. I double-click on my new batch-file to run it.

2. I to quickly edit that same batch-file.

Do I have to constantly change the permissions back and forth?
Or constantly rename the file *.bat to *.txt back and forth?

Dave Taylor said, on February 28, 2011 11:56 AM:

Set it up so you can double-click to launch it, then Control-Click on it and choose "Open with..." TextEdit (or similar) and you should be good...

peter said, on March 16, 2011 5:05 AM:

Hi. Great help with the comment above, just on this comment (in apple-script) zou need double-quotes:

as in

do shell script "echo hi"
instead of
do shell script 'echo hi'

harry Calder said, on July 4, 2011 10:19 AM:

hi, how about make a script to execute the command
java -Xincgc -Xmx1G -jar crafty.jar
in the file user/desktop/server?

arbinger said, on December 9, 2011 2:42 PM:

Hi, I just released a source via github called 'bashapp' that will compile your bash script into a binary (C source) and also create a Mac application that you can click on from Finder. It's here, if anyone wants to take a look.

https://github.com/arbinger/bashapp

Thanks, James

Lando said, on December 20, 2011 8:15 AM:

You can also use Platypus to create a native Mac app from a shell script.

colin said, on January 2, 2012 6:53 AM:

Quick question, but there's a back story. I'm trying to write a shell script that will enter a terminal command, specifically something that opens a file using Python. I wrote a text file and saved it as a .sh file, then used the "open with" feature to always open it with terminal. It works.

But now I'm curious about this Applescript thing. Question is: why does break when it tries to use the "python" command as I use in Terminal?

Dave Taylor said, on January 2, 2012 3:33 PM:

I have to admit that I am completely clueless about Applescript, Colin. Perhaps someone else can explain?

Bruce Brown said, on January 25, 2012 7:43 PM:

Colin,

Just off the top of my head, here are three possibilities for why your AppleScript script that uses the "Do Shell Script" AppleScript command isn't working:

o Using a different shell in Terminal vs. in Do Shell Script; or

o Using a different starting directory in Terminal vs. in Do Shell Script; or

o Using different I/O redirection in Terminal vs. in Do Shell Script.

Failing the above, I hope that this "application note" for the Do Shell Script command in AppleScript will get you pointed in the right direction. It should be REQUIRED SKIMMING for anyone who uses the Do Shell Script command:

Technical Note TN2065
do shell script in AppleScript

http://developer.apple.com/library/mac/#technotes/tn2065/_index.html

Over time, the above link might fail because of "link rot." If that happens, I suggest searching Apple's Developer website on "tn2065" (without the quotes).

I have found that wrapping an Unix command or Unix shell script invocation command (the name of the script) in an AppleScript is a great--and quick--way to turn any shell script or Unix command into an OSX application. Just save it out of the AppleScript Editor, being sure to select the "Application" choice for the "Format" on the drop-down menu in the "Save" dialog box. That will create an OSX application that can be double-clicked to launch, can be put into your Dock, etc, and can be generally used just the same as any other OSX application.

-B.

Art said, on February 23, 2012 8:33 AM:

re: script file location, you mention "...if you have the script in one of the directories in your PATH". Is there a common/typical/usual directory where people store their script files on Mac OS X?
My current path is this: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:
So I'm wondering if I should store my script files in one of those directories or create a new one and add it to the PATH.
Thanks!

Starbucks coffee cup I do have a lot to say, and questions of my own for that matter, but first I'd like to say thank you, Dave, for all your helpful information by buying you a cup of coffee!

I do have a comment, now that you mention it!











I will never send you any unsolicited email. Ever.






Check This Out Too...

 
Look for Answers
Need Help? Ask Dave Taylor!


Follow Me on Pinterest

Find Me on Google+
ADT on G+
© 2002 - 2013 by Dave Taylor. All Rights Reserved.

Note: This web site is for the purpose of disseminating information for educational purposes, free of charge, for the benefit of all visitors. We take great care to provide quality information. However, we do not guarantee, and accept no legal liability whatsoever arising from or connected to, the accuracy, reliability, currency or completeness of any material contained on this web site or on any linked site. Further, please note that by submitting a question or comment you're agreeing to my terms of service, which are: you relinquish any subsequent rights of ownership to your material by submitting it on this site. My lawyer says "Thanks".
"Ask Dave Taylor®" is a registered trademark of Intuitive Systems, LLC.