What is the shebang?

<aside> ⚠️ The shebang line is crucial for making scripts executable directly from the command line. Without it, you would need to explicitly specify the interpreter each time you run the script.

</aside>

The shebang, also known as a hashbang, is the first line of a script in Unix-like operating systems. It begins with a hash character (#) followed by an exclamation mark (!). This special sequence is used to specify the interpreter that should be used to execute the script.

For example, if you have a Bash script, and bash is in /bin, you would start it with:

#!/bin/bash

This indicates that the script should be executed using the Bash shell.

Here's how it works:

  1. When you run a script from the command line, the system looks at the first line to determine which interpreter should be used.
  2. If the line starts with #!, the system reads the rest of the line to find the path of the interpreter.
  3. The specified interpreter is then used to execute the script.

For example, if the shebang line is #!/usr/bin/python3, it tells the system to use Python 3 from the directory /usr/bin to execute the script.


Examples

Example Python3 script with a shebang

#!/usr/bin/env python3

import argparse
import sys
import math

def calculate_square_root(number):
    try:
        result = math.sqrt(number)
        return result
    except ValueError as e:
        return None, e

def main():
    parser = argparse.ArgumentParser(description='Calculate square root of a number')
    parser.add_argument('-i', '--input', type=float, required=True, help='Input number')
    
    args = parser.parse_args()

    input_number = args.input

    result, error = calculate_square_root(input_number)

    if result is not None:
        print(result)
    else:
        sys.stderr.write(f"Error: {error}\\n")
        sys.exit(1)

if __name__ == '__main__':
    main()

Example BASH script with shebang

#!/usr/bin/bash

print_hello_world() {
    local n=$1
    for ((i=0; i<n; i++)); do
        echo "Hello World"
    done
}

# Check if the user provided an argument
if [ $# -eq 0 ]; then
    echo "Usage: $0 <number>"
    exit 1
fi

N=$1

# Check if N is a positive integer
if ! [[ "$N" =~ ^[0-9]+$ ]] || [ $N -le 0 ]; then
    echo "Error: Please provide a positive integer as an argument."
    exit 1
fi

# Call the function to print "Hello World" N times
print_hello_world $N

exit