HPurpose of Shell-Script Headers

Nilesh Katuwal Feb 02, 2024
HPurpose of Shell-Script Headers

In programming, a shebang is a sequence of hashtags and an exclamation mark #! at the beginning of a file. The entire path to the interpreter that will execute the file code is then supplied /bin/bash.

After that, there’s the code itself. The interpreter usually ignores the shebang line since the # character is a comment marker in many scripting languages.

Syntax of Shebang

A shebang interpreter directive takes the following form.

#!interpreter [optional-arg]

In most cases, an interpreter is the only absolute route to a program that can be run.

The optional argument is a single parameter represented by a string. White space is not required after #!.

A file can be executed in Linux under the following conditions.

  • The interpreter’s file has the execute permission and contains code that the kernel can directly execute.
  • The file has a sysctl wrapper defined, such as executing any .exe files using wine.
  • The file contains a shebang.

An interpreter on Linux can alternatively be a script. A succession of shebangs and wrappers produces a directly executable file that reverses the scripts’ order as inputs.

Examples of Shebang

Here are a few examples of typical shebang lines.

#!/bin/sh

Use the Bourne shell, or another compatible shell, to run the file, which is presumed to be in the /bin directory.

#!/bin/bash

Use the Bash shell to run the file.

#!/usr/bin/pwsh

Use PowerShell to run the file.

#!/usr/bin/env python3

Use a Python interpreter to run it, and look for it using the env program search path.

#!/bin/false

It returns a non-zero exit status, signaling failure instead of doing nothing. It is used to prevent a script file designed for usage in a certain context, such as sh/bash, from running independently.

Purpose of Shebang

By removing the need to precede scripts with their interpreters on the command line, interpreter directives allow scripts and data files to be used as commands, obscuring the intricacies of their implementation from users and other programs.

The first line of a Bourne shell script identified by the path some/path/to/foo is below.

#!/bin/sh -x

It’s run using the parameters bar and baz.

some/path/to/foo bar baz

It yields the same result as the following command line.

/bin/sh -x some/path/to/foo bar baz

If the Bourne shell is specified by /bin/sh, then all the shell commands in the file some/path/to/foo are run with the values bar and baz for the positional variables $1 and $2, respectively.

The interpreter also ignores the entire shebang line since the initial number sign initiates comments in the Bourne shell language and many other languages interpreters understand.

The interpreter decides whether or not to ignore the shebang line.

Related Article - Linux Bash