What is the Function of Shebang in Linux?

bash shebang linux

The #! characters form a magic number. We embed these magic number in any scripts under UNIX / Linux operating systems to tell the kernel what interpreter to execute, to read our script. Like Linux shell, Python, Perl and R interpreters. You might have noticed all Linux shell and Perl / python script starts with the below line:

#!/bin/bash

OR

#!/usr/bin/env python

OR

#!/usr/bin/env perl

OR

#!/usr/bin/env Rscript

Now we will write a program file for Python language. we can execute this program by calling the interpreter directly without adding shebang line like below.

python_script

import sys

def greeting(name):
    sys.stdout.write("Hello" + name + "\n")

name = "Omar"
greeting(name)

For executing the code, we will mention python before name of the file.

python python_script.py
Output
    Hello Omar

Also we will write a program file for R language. we can execute this program by calling the interpreter directly without adding shebang line like below.

r_script

print("hello world")

For executing the code, we will mention Rscript before name of the file.

Rscript r_script.R
Output
    "hello world"

How to make executable file

to make executable file we should add shebang line #!/usr/bin/python to the top of script and changing the mode of the file to be executable.

python_script

#!/usr/bin/python
import sys

def greeting(name):
    sys.stdout.write("Hello" + name + "\n")

name = "Omar"
greeting(name)

To make the file is executable, type the command below.

chmod +x python_script.py

Now we can just run the file and it will be interpreted by python.

./python_script.py
Output
    Hello Omar

Large computer cluster

The path /usr/bin/python will probably work for most default systems but might not work on things like a large computer cluster. So we will use the program env to get the right interperter.

#!/usr/bin/env python
import sys

def greeting(name):
    sys.stdout.write("Hello" + name + "\n")

name = "Omar"
greeting(name)

We can do the same for any program like Rscript as well.

  #!/usr/bin/env Rscript
  print("hello world")

Read Also:

Ahmed Abdalhamid 8:01 am

Comments

Your email address will not be published. Required fields are marked *

All comments are subject to moderation.