Question

How can I write a bash script in Mac OS X that opens a Terminal window in a specific directory? I'd assume something like:

open /Applications/Utilities/Terminal.app

But that does nothing (maybe it's loading the Terminal application which is already open instead of launching a new Terminal window). And of course it doesn't cd into a directory as I haven't specified that...

Was it helpful?

Solution

Here is a small script I knocked up :

#!/usr/bin/osascript
on run argv
  set dir to quoted form of (first item of argv)
  tell app "Terminal" to do script "cd " & dir
end run

If you save this and make it executable

chmod +x script_filename

and then run it

script_filename ~/Desktop

then it will open up a new terminal window and change to the directory in the argument.

OTHER TIPS

As of Mac OS X Lion 10.7, if you open a folder with Terminal it will create a new terminal at that location. e.g., you can drag a folder onto the Terminal application icon, or into a tab bar to create a new tab, and there are Services (New Terminal at Folder) you can use from the contextual menu to open a new window or tab for a selected folder in Finder or other applications (or even a pathname selected in text).

To do the equivalent from the command-line (or a shell script):

open -a Terminal /path/to/folder

This is the command-line equivalent of dragging the folder onto the Terminal application icon. (You can also supply a full path for Terminal if you want to specify a particular copy/version of the application.)

I'm not sure if the following works from a bash script, but at least I found out how to open specific tabs in specific directories:

In the Preferences, under Settings, you copy the profile that you would normally like to use. Under Shell, you can tell it to "Run command": cd /some/directory. You will also want to check "Run inside shell". Optionally, you can specify a title under Window.

Add more profiles in this manner.

Then close all terminal windows, then open a profile in a new window, plus another profile in a new tab, plus another profile in a new tab. Now you have a window with three tabs. Save this as a window group.

From now on, whenever you have Terminal running, you can open this window group, and you will get a new window with these tabs in these directories.

Open question: how do I tell Terminal to open a new window group, from a bash script?

Licensed under: CC-BY-SA with attribution
Not affiliated with apple.stackexchange
scroll top