How do I make this file.sh executable via double click?

Jacob picture Jacob · Dec 7, 2011 · Viewed 292.5k times · Source

First off I'm using Mac.

Next, I need to execute this "file.sh" we will call it. Everytime I need to execute it I have to open Terminal and type:

cd /Users/Jacob/Documents/folderWithFileInIt
bash file.sh

This is okay, but I feel like it would be a lot quicker if I make the file execute on double click, don't you think?

So my question is, how do I make this file executable via double click?

My ideas were either:

a) type something like chmod into terminal and change permissions?

b) make a file, put code I wrote above in it ^ and then make that file executable?

c) make an automation somehow to do this?

Which way is best, or is there an even better way? Also please explain as much as you can, I'm new to Terminal. Thanks.

Answer

Chris Page picture Chris Page · Mar 10, 2012

By default, *.sh files are opened in a text editor (Xcode or TextEdit). To create a shell script that will execute in Terminal when you open it, name it with the “command” extension, e.g., file.command. By default, these are sent to Terminal, which will execute the file as a shell script.

You will also need to ensure the file is executable, e.g.:

chmod +x file.command

Without this, Terminal will refuse to execute it.

Note that the script does not have to begin with a #! prefix in this specific scenario, because Terminal specifically arranges to execute it with your default shell. (Of course, you can add a #! line if you want to customize which shell is used or if you want to ensure that you can execute it from the command line while using a different shell.)

Also note that Terminal executes the shell script without changing the working directory. You’ll need to begin your script with a cd command if you actually need it to run with a particular working directory.