Write your first shell script

If you have used a mac for a long time and never opened up the terminal, you are really missing out on a productivity workhorse. The power comes from the simplicity. At it’s core the command line is all about typed input. However, if you find yourself using the same commands over and over, you could really crank up the geek by making your own shell scripts. Here is how to do just that.

Make a script directory

Finding a place for your scripts is wise so you can keep them separate from system scripts or scripts you may download. I keep them in my home folder in a folder called bin.

mkdir ~/.bin

Next your going to need to set up the path so your shell can find your scripts, you can do that by adding the path to your .bash_profile.

Here is an example using the nano editor in OSX, but feel free to use any text editor you want. Nano is a great command line editor because it is almost everywhere and has a low learning curve unlike vim.

nano ~/.bash_profile

And place this line at the top:

export PATH=$PATH:~/.bin

Close and save the file by pressing ctrl-x (Looks like ^X) and press y and then enter to save as the same name.

Create the script

cd ~/.bin # Go to your bin directory
touch hello # Creates a script named hello
chmod +x hello # Makes executable "Off With His Head"
nano hello # Opens in nano editor

In nano copy any paste the following:

echo Hello $1 

Line 1: This is a bash script, which can be found at /bin/bash.
Line 2: The $1 is a variable representing the first argument.

Run the script

hello World
// Hello World

In the spirit of don’t repeat yourself, lets make a script to make making scripts easier. We will call it ‘makescript’.

cd ~/.bin
touch makescript
chmod +x makescript
nano makescript

Enter the following and save the file:

cd ~/.bin
touch $1
chmod +x $1
echo $1 > \#!/bin/bash

Now you can use the following to create any scripts you like:

makescript nameofscript

I havn't scratched the surface so I recommend this bash good tutorial. The possibilities are endless. Happy Hacking.