How to run Terminal commands from Finder?

I would like to put a series of Terminal commands into a file, then run the commands by double-clicking on the file in Finder. I've found a number of sources on how to do this on the internet, but nearly all include comments from other users saying "this didn't work for me". I've not found a definitive "this is how to do it".


I created a test file using TextEdit, named it test.command, and saved it to my desktop. The file contains these commands:


!/bin/sh

chmod +x ~/Desktop/test.command

echo "hi there"

echo "hi again"


When I double-click on the file, however, it sometimes just opens in Finder. Other times, I get an error message saying that I do have permission to run the file. I thought the chmod command was supposed to handle the permission, but maybe I'm not using it correctly.


Can anyone help?

iMac, OS X Yosemite (10.10)

Posted on Feb 8, 2016 4:11 PM

Reply
3 replies

Feb 9, 2016 6:29 AM in response to pomme4moi

#!/bin/sh


you need the # followed by the ! as the very first 2 characters of the file.


And since bash is the default shell, you should most likely actually say


#!/bin/bash


The chmod +x command needs to be done after creating the test.command file, not inside of it.


Another way to execute shell commands is via Automator -> Run Shell Script


Automator does not need to open a Terminal session to process the commands. But if you want to have the command display something, it might be simpler to use a .command file, although there are ways to display things from an Automator app as well.

Feb 9, 2016 8:41 AM in response to pomme4moi

It is the file permissions. It is stored as part of the file metadata (the same as the name, the file size, the file owner, etc...). It is a one time thing. You are setting the execute permission so the operating system knows there is executable code inside, and not your grocery shopping list. Then again, maybe trying execute your grocery shopping list might be interesting 😀

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

How to run Terminal commands from Finder?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.