By James Harrison from Unsplash

SHEBANG #!/bin/sh

Christoph Krassnigg
2 min readMay 18, 2021

--

Every developer might encounter a script like the following:

#!/usr/bin/python3
print("Hello world!")

People get often told that they should use the #!/usr/bin/python3, without even knowing why. It does not differ if the first line is there or not because Python will handle the first line as a comment. The combination of a hashtag and an exclamation mark does something important, and there are good reasons why a developer should place it at the top.

This article will cover all the confusing questions, which come up when someone sees a shebang for the first time.

What is the shebang used for?

After the shebang, there is usually a path to the interpreter of the current script. The path after the shebang shows the system what type of script we want to execute. Let us imagine we have a file called “hello.sh” with the content:

#!/bin/sh
echo "Hello!"

If we execute it, we get the text “Hello” printed. Then we try to remove the shebang.

echo "Hello!"

Removing the shebang does not affect anything. The system can still guess that we are executing a shell script because of the file ending. So what will happen if we rename the file from “hello.sh” to “hello”?

Nothing. The script will still execute as above because, in scenarios like this, a shell script, the system’s default choice is.

What if we want to write a python script instead?

#!/usr/bin/python3
print("Hello Python3!")

The system would run it as a python script, as long as the file has a .py extension or a shebang.

If none of those two factors apply and we do not execute it with the python command, we get a syntax error. The system wants to execute our python script as a shell script, which does not work out.

If the “python” command executes the script, then it is clear that it will work, but it may not be instantly clear for an external viewer. It could be a python script, but then just trying “./script_name” in the shell should work if you are not sure. This is where the shebang comes in place. If the developer provided one, then the script will work without any problems. Otherwise, the viewer needs to look at the script and understand what it does.

Conclusion

A shebang is not necessary but should always occur in well-written scripts. It guarantees that the system will execute it properly, even without any file extension.

--

--

Christoph Krassnigg

Developer at block42. Student. Java fanatic. Loves to write about techy things.