So you have created a script that you want to use by just typing its name in the command line, but don’t know how to do it? Tech 4 Freelancers explains. UNIX and UNIX-like operating systems and even Windows use a specific environment variable called PATH to know where to look for executable files.
Note: Linux and macOS environment variables are case-sensitive, meaning that you’ll PATH (in all caps) is a legal environment variable, whereas path is not. Windows is case-insensitive, so either way is fine.
The PATH environment variable
To see the value of your PATH environment variable, you need to open the Terminal and type the command
The default value of PATH on macOS Sierra is as follows:
On Ubuntu, the default PATH value is
In case you didn’t already notice, these values are a list of paths where the terminal will search for runnable applications. It should be noted that bash will not attempt to crawl directories recursively: if you, for any reason, want to run a program in the /usr/sbin/myfolder folder, you’ll have to manually add an entry for that folder in PATH.
UNIX and UNIX-like operating systems use a special sequences of characters to tell the command line interpreter (in most cases, bash) what language that particular script is written in. Such sequence of characters is called a shebang and is generally found on the first line of the script. It follows this scheme:
In order to find out the path to the interpreter your script will use, you can type the which command in a terminal.
So, in order to make a bash script executable, you will need to add the following shebang at the beginning
or, if your script is written in Python,
The execute bit
UNIX systems do not treat file extensions specially, unlike Windows. To make a script executable, you need to set its execute bit accordingly. This can be done using the chmod command.
Imagine you have created a script called “hello” in your desktop. To make it executable on macOS, you’ll need to use
chmod +x /Users/YourUsername/Desktop/hello
On Linux, you’ll use
chmod +x /home/YourUsername/Desktop/hello
Replace YourUsername with your actual username. In case you don’t know it, you can retrieve it with the whoami command.
Moving the script to a folder in your PATH variable
In order for the command-line interpreter to find your script, it will need to be moved to a path listed in the PATH environment variable. To do this, use the mv command. On macOS:
sudo mv /Users/YourUsername/Desktop/hello /usr/local/bin
And on Linux:
sudo mv /home/YourUsername/Desktop/hello /usr/local/bin
Note: For security purposes, macOS will prevent you from moving files to any of the default PATH destinations except /usr/local/bin. Linux has no such restriction.