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 spot for your scripts
Finding a place for your scripts is wise so you can keep them separate from system scripts. I keep mine in my home folder in a folder called .bin (Yes, it’s hidden).
Create the folder like so:
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 choosing Yes to save as the same name. (Press y and then enter, for the type first read later people)
Create the script and set permissions
Now we need to create a script to live in his/her new home. To keep things simple and make sure the above steps worked we will just do the standard “Hello World” test. Anything following the ‘#’ is a comment and is not ran.
cd ~/.bin # Make sure we are in the right spot
touch hello # Creates a script named hello
chmod 700 hello # Makes executable "Off With His Head"
nano hello # Opens in nano editor
In nano copy any paste the following:
!#/bin/bash
echo Hello $1
The first line is saying this is a bash script, which can be found at /bin/bash.
The second line is are actual script, the only special thing about it is the $1 sign which is a variable for any input following the script. You could have multiple variables in chronological order by using $2, $3 and so on.
Run the script like a boss
Now we should be able to run the script to desired effect by typing the following:
hello World
If you get any errors make sure your script is in the right place by typing:
cd ~/.bin # go to the spot
ls # show files, it should output back hello
If it is in the right place set the permissions with:
sudo chmod 700 hello # sudo will prompt you for an admin password
Finally check to make sure your path is set correctly:
nano ~/.bash_profile
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 700 makescript
nano makescript
Enter the following and save the file:
#!/bin/bash
cd ~/.bin
touch $1
chmod 700 $1
echo $1 > \#!/bin/bash
Now you can use the following to create any scripts you like:
makescript nameofscript