Shebangs: Scripting Made Easier

Shebangs: Scripting Made Easier

Shebang? Hashbang? Wot Bang?

Shebang?

Shebang, also known as Hashbang is a combination of characters #!. It specifies which interpreter is supposed to run the script.

Shebangs are always supposed to be at the top of the script.

They are helpful when scripting.

How to write a shebang?

To write a shebang, firstly we type #! followed by the path of the interpreter. For example, for sh we would write it as

#! /bin/sh

and for Python we'd write it as

#! /usr/bin/python

Where is my x interpreter located?

We can find the path of our binary by using which command.

which usage

$ which programname

For example, for python we'd do:

$ which python
/usr/bin/python

This gives the path of python in my computer, it may be different in your computer.

How does it actually work?

To know how it works, let's first create a simple script name.sh

echo -n "Enter your name: "
read name
echo "My name is $name"

All this script does is, reads input, and echoes it.

To run it, we simply do

$ bash ./name.sh
Enter your name: Raahim
My name is Raahim

Notice how we run the file with bash? What if we didn't want to type bash everytime we wanted to run the file. That's where shebangs come in handy. Let's add one to our file

#! /bin/bash
echo -n "Enter your name: "
read name
echo "My name is $name"

Now to run the file, we'd do

$ ./name.sh
bash: ./name.sh: Permission denied

Unfortunately, we get a permissions error. Nothing to panic about though, it's as expected. Let's take a look at our file's permissions.

$ ls -l name.sh
-rw-r--r-- 1 raahim raahim 75 Jul 30 17:08 name.sh

-rw-r--r-- these are the permissions of our file. r means read, w means write and x means execute. We need x to be able to run our file. Let's change that

$ chmod +x name.sh
$ ls -l name.sh
-rwxr-xr-x 1 raahim raahim 75 Jul 30 17:08 name.sh

Let's try to run our file again

$ ./name.sh
Enter your name: Raahim
My name is Raahim

Voila!

How to avoid shebang?

Sometimes, maybe we want to run a file with a different interpreter. For example, maybe we want to run a script with zsh instead of bash.

Specifying an interpreter explicitly ignores the shebang. For example to run our name.sh file with zsh we'd just do

$ zsh ./name.sh

Conclusion

  • Shebangs are also known as hashbangs
  • Shebangs are used to specify interpreters of the script
  • Shebangs start with #!
  • To make shebangs work, the path needs to point to an executable and the file needs to have execute permissions
  • which can be used to find path of our binary/executable
  • chmod +x filename can be used to add execute permissions to the file
  • ./filename to run the file