1. Overview

In this tutorial, we’ll see how to use the shebang (“#!”) to tell our Unix-like system how to interpret an executable file.

2. Theory

When we try to run an executable file, the execve program is called to replace the current process (bash shell if we are using terminal) with a new one and decide how exactly that should be done.

If we try to run a text file, execve expects the first two characters of the file to be “#!” (read “shebang” or “hashbang”) followed by a path to the interpreter that will be used to interpret the rest of the script.

3. Writing a Shell Script

The most common need for using shebang appears when we’re writing shell scripts.

Let’s write a simple script that will greet the user:

#!/bin/sh
echo "Hello, ${USER}"

“/bin/sh” is actually the symlink to an sh-compatible implementation of sh (Shell Command Language).

In most cases, it’ll be bash (Bourne-Again SHell), but if we want to secure portability, we should use the symlink.

Also, remember that the script must be executable for this to work. When we create a new script file, we can make it executable using the chmod command:

chmod +x name_of_the_file

4. Using Other Interpreters

We may want to write easily executable scripts using different interpreters than sh — and in fact, we can use any ELF executable.

For example, here’s a technically correct (although arguably not very useful) script that will print itself upon execution:

#!/bin/cat
Hello World!

5. Using the User’s PATH

In previous examples, we used locations of programs that we know for sure because they’re standard in Unix-like systems.

Unfortunately, that’s not always the case. However, there is one trick that can help us in that kind of situation.

We can use the env program and pass the name of our target interpreter as its argument. Then env will look up the interpreter in the user’s PATH variable.

Let’s write one more “Hello world” script, this time using Node:

#!/usr/bin/env node
console.log('Hello world!');

6. Conclusion

In this quick article, we explored using shebang to instruct the system on how to interpret our script.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.