#! – Usually nicknamed shebang, shabang, hashbang, poundbang – we’ll stick with shebang for the duration of this article.
It is found at the beginning of countless Linux shell scripts – but what actually is it? Let’s break it down.
It Usually Looks Something Like This
#!/bin/bash
The #! appears at the beginning of the file, usually on the first line, followed by the path to an executable (in this case, the bash shell).
It’s a Comment
It starts with a #, so it’s not executed as part of the script itself – it does affect how the script operates, however, because…
It Proceeds an Interpreter Directive
The shebang tells the system which interpreter to use to run the script by giving it a path to the interpreter executable.
- It is usually placed at the beginning of the file, on the first line, so that the correct interpreter can handle the rest of the file.
- The path given must be an absolute path to a suitable executable
- The shebang line may contain options that can be passed to the interpreter, but support on this varies depending on your environment – it’s safest to include only a single option.
Examples
Below are some #! examples and what they mean:
bash
#!/bin/bash
Placing this line at the beginning of a script will tell the system it should be executed using the bash shell executable.
zsh
#!/bin/zsh
Placing this line at the beginning of a script will tell the system it should be executed using the zsh shell executable.
Read our article on the differences between bash and zsh here!
Python
#!/usr/bin/env python3
Execute the script using Python 3. Notice here that rather than specifying the path to the python3 executable, this line finds the python3 executable currently defined for the users’ environment.
Nothing!
#!/bin/false
Returns a failure status code and doesn’t execute the script. Used in scripts that are not intended to be directly executed.
Bypassing the #!
If you are running a script with a #! like so:
./myscript.sh
Here myscript.sh is your script’s name – the shebang is used to determine what interpreter is to be used.
The above can be done only on scripts where the current user has the execute permission.
If, however, you do the following:
bash myscript.sh
…the shebang line is not used to determine which interpreter to used, as we have specified bash in the command used to call it. Only read permission for the script is required to do this, as the script isn’t being executed, bash is being executed.