BASH scripts on Mac OS X

I learned today how to use a BASH script on Mac OS X.

Just create a text file and put #!/bin/bash on the first line, and then write the rest of your BASH script and save.

Then make the file executable by opening Terminal and running
chmod +x scriptname.sh

Then you should be able to run it from the Terminal command line.

To make it so you can run the script by just double clicking on it in Finder, just change the extension of the script file to be .command

See Introduction to Open Source Scripting on Mac OS X


Anonymous said...

yeah im learning about this stuff to
if you want to write the script in terminal just type
then Terminal will become a text editor.
happy scripting

Yarin said...

IMPORTANT: Be aware that if you run your .command script by double-clicking, it uses the user's home directory as the working directory, and NOT the directory the script is in.

It's a great way to unintentionally affect every file on your system instead of just the ones in the dir you are targeting. (speaking from experience)

Solution: If you need to reference the current directory in a .command script, use `dirname $0` instead of `pwd`