How to turn your scripts into commands in Linux and Mac command lines / terminals
En Español  

First create a bin folder in under your user.

To see where we are we use pwd and to see where is our user folder we can use echo $HOME

pwd
echo $HOME

and then switch to your userfolder (if you just opened the console you should be there already). The command cd with no parameters bring you to the home folder, otherwise you can use cd $HOME

cd
cd $HOME

The folder does not have to be named “bin”, it can be named whatever you want. I name my folders for scripts “bin” as the systems usually use a folder named “bin” for executables.

mkdir bin
cd bin

Now lets make a make a file, it can have an .sh extension, or no extension at all.

touch thing
touch thing.sh

Now we edit the file that we want, I created both for this example but it can be any of them. I normally use vim to do so, but you can use something such as nano if you don't use vim (to exit vim in case you get in, press ESCAPE, then type :q! and press ENTER).

nano thing
nano thing.sh

Then the important part of the script. The first line says which sort of script it is. Normal options are “Bash”, but it can be “Python”, “Perl”. For this article I am going to use Bash as it is a Bash script.

#!/bin/bash

And a simple “Hello World!” will do.

echo “Hello World!”

Now, lets turn this script executable:

chmod u+x thing
chmod u+x thing.sh

Now, we have the script that we want and it is executable, we can run it by going to the folder and using ./ before the script's file name, but we want to have it executable from wherever we are, so lets go to the next part.

All folders with scripts reside in the PATH variable. We will add our bin folder to this.

We already have a $HOME variable, this will print the HOME address. So we will update $PATH with:

export PATH=$HOME/bin:$PATH

Now $PATH has $HOME/bin plus the whole $PATH.

We can now use, in this terminal, “thing” or “thing.sh”, depending on what you did. But it is only this terminal, we want it to be available in every terminal that we open from now on, so lets add the command to our .bashrc in Linux or to our .bash_profile in Mac

echo “export PATH=$HOME/bin:$PATH” >> $HOME/.bashrc

This will work on a Linux distribution such as Ubuntu, Linux Mint or Raspbian, basically Debian based. However, in Mac we can add this line to .bash_profile instead to accomplish the same.

echo “export PATH=$HOME/bin:$PATH” >> $HOME/.bash_profile

And there we have it.