Thursday, March 31, 2011

Using custom shell scripts on Linux & OSX

You need to create a custom shell script and would like to run it from anywhere on your system.

1. Create a `bin` directory to store your script.
machine:~ user$ mkdir ~/bin

For Linux users this will create /home/[user]/bin, for OSX you'll have /Users/[user]/bin. You could name this directory whatever you'd like, but bin seems fitting.

2. Modify .bashrc or .bash_profile to put `bin` on your path.

If you're comfortable with vi you can: (Alternatively use any text editor you are comfortable with)

machine:~ user$ vi ~/.bash_profile [OSX]
user@machine:~$ vi ~/.bashrc [Linux]

Either way, add the following line:
PATH=$PATH:$HOME/bin

3. Save and exit.

4. Source your file for it to take effect:

machine:~ user$ . ~/.bash_profile [OSX]
user@machine:~$ . ~/.bashrc [Linux]

5. Now you can drop a shell script into your bin directory and have executable from anywhere on your filesystem (don't forget to make it executable!)

Example:

Last login: Thu Mar 31 11:07:30 on ttys004
machine:~ user$ pwd
/Users/user
machine:~ user$ touch example
machine:~ user$ vi example
...

#!/bin/sh
echo "Somewhere in Russia a little girl is warming up with your max."

...
machine:~ user$ mv example ~/bin/
machine:~ user$ chmod +x ~/bin/example
machine:~ user$ ls -l ~/bin | grep example
-rwxr-xr-x 1 user staff 80 Mar 31 14:25 example
machine:~ user$ cd /tmp/
machine:tmp user$ example
Somewhere in Russia a little girl is warming up with your max.
machine:tmp user$


Fin

Lift weights - Lift spirits

No comments:

Post a Comment