Write an AppleScript to boot a Shell Script at Runtime on your Mac

Published by in January, 2017

Categorized in: Dev Stuff

Tags: BASH Scripting  

Curious how to boot up a shell script at runtime on your Mac? Here's a straight forward approach to writing an AppleScript to accomplish that, that almost anyone should be able to follow. First we will create an AppleScript to startup Terminal. Then we will modify our .bash_profile with an alias command to run a particular script and then we will execute the script.

The is the followup from my previous post on how to automate projects with a shell script in Terminal/command line: Automate your dev projects using a shell script! Note: At the time of this post I'm on OSX Sierra.

First open up Apple's Automator.app using the Spotlight Search

Click on Application and then click on Run AppleScript. Paste the following:


on run {input, parameters}
	
	tell application "Terminal"
		activate
	end tell
	
	return input
end run

You've now created an AppleScript that will open Terminal. You can test it by clicking Run.Now save the file, I have my file saved in a BASH-SCRIPTS folder at the home directory of my system. I called my AppleScript start-up.app.

Now that you have that saved- close Automater and go to System Preferences > Users & Groups, and click on Login Items at the top. Then click the + icon and navigate to your BASH-SCRIPTS folder and select the start-up.app file. Great now you have successfully told your script to run when you login, which will activate Terminal.

You might notice that you could have easily just added the Terminal Application without creating an AppleScript, but let's say you wanted to startup a shell script inside the AppleScript or some other special instructions- you now have a head start.

Now let's modify your BASH profile (.bash_profile), and if you have not created one before I suggest you go here: My Mac OSX BASH profile

Create a function to run a shell script of your choice. Paste this inside your .bash_profile


start () {
      osascript -e "tell application \"Terminal\" to do script \" $HOME/BASH-SCRIPTS/start-project.sh\" in front window" \" > /dev/null 2>&1
    }

In shell script language- this is how you declare a function, and because it's in your .bash_profile, all you do when Terminal is open is type start, and that will run the function - which as you can see is an AppleScript command (osascript) telling Terminal to do a script that we have in our home directory, inside of the BASH-SCRIPTS folder called start-project.sh and run it in the front window. If that piece of code isn't there and what follows- it will open up a new terminal window- but you already have one open.

Again if you want to see what I've written inside of start-project.sh to automate your project workflow, take a look here.