How to Use Shebang in Bash Scripts

July 13, 2023

Introduction

A shebang (also known as a hashbang or sha-bang) is the #! character sequence at the beginning of a script in Unix-like operating systems. The shebang is followed by the interpreter or the command that should be used to execute the script.

When running a script, the OS looks for the shebang line and uses the specified interpreter or command to execute the script.

In this tutorial, you will learn to use the shebang in Bash scripts.

How to use the shebang line in Bash scripts - a tutorial.

Prerequisites

What Does Shebang Mean in Bash?

In Bash, the term "shebang" refers to the first line of a Bash script that specifies which interpreter will be used when executing the script. The shebang line allows users to leverage the power of different interpreters or customize the script execution behavior.

Bash scripts usually start with one of the following shebang lines:

#!/bin/bash

or

#!/usr/bin/env bash

When you run the script, the operating system reads the shebang line and runs the specified interpreter to process the script file.

Using Shebang in Bash Scripts

When writing Bash scripts, understanding and using the shebang line can enhance script execution and portability. Including the appropriate shebang at the beginning of a Bash script ensures that the desired shell interprets the script correctly.

Shebang allows the use of different interpreters or programming languages in scripts and facilitates script execution and compatibility across platforms.

The sections below will provide examples of using the shebang line in Bash scripts.

Use Bash Interpreter

Bash is the default command-line interpreter in Linux and macOS operating systems. The following Bash script example uses a shebang line that explicitly instructs the OS to use the Bash interpreter located at /bin/bash to run the script.

Follow the steps:

1. Create the script using a text editor of your choice:

nano [script_name]

2. Paste the following lines:

#!/bin/bash
echo "Hello, world!"
Specifying the Bash interpreter in the shebang line.

The script lines below the shebang contain Bash commands which are interpreted and executed using the Bash interpreter. In this case, it is the echo command.

3. Make the script executable by using the following syntax:

chmod +x [script_name]

4. Run the script using the following syntax:

./[script_name]
Running a script with the Bash interpreter specified in the shebang line.

The OS reads the shebang line and uses the specified interpreter (in this case, Bash) to execute the script and print the line using the echo command.

Use Bash Interpreter Through env

The env command allows users to display the current environment or run a specified command in a changed environment. The following shebang line uses the env command to locate the Bash interpreter in the system's default paths:

#!/usr/bin/env bash

Using the env command in such a way provides flexibility in case the Bash interpreter is installed in a different location.

For example:

Specifying the bash interpreter in a shebang line using the env command.

Running the script produces the same output because env finds the Bash interpreter in the $PATH and executes the script:

Running a script which uses env to locate the interpreter.

Use POSIX Shell Interpreter

The POSIX (Portable Operating System Interface) Shell is the standard Unix shell. The benefit of using the POSIX shell is that it makes scripts portable and more likely to run consistently across different Unix-like systems. This behavior is not typical for other shell types.

The POSIX shell is located at /bin/sh in the system. That location should be specified in the shebang line by using:

#!/bin/sh

This shebang line specifies the POSIX shell interpreter. This ensures compatibility with a broader range of Unix-like systems that may not have Bash installed but have a POSIX-compliant shell.

To test using the POSIX shell interpreter and check if a string matches a regular expression, follow the steps below:

1. Create a new script.

2. Paste the following lines:

#!/bin/sh
SOME_VAR="foo-bar-3"
if echo "$SOME_VAR" | grep -P '\d$';then
  echo "it ends in a digit!"
else
  echo "it doesn't end in a digit!"
fi

Note: Read our tutorial and learn to use grep regex.

3. Make the script executable.

4. Run the script:

Running a script with the POSIX interpreter specified in the shebang line.

Note: Keep in mind that the POSIX shell interpreter doesn't provide some of Bash's advanced features and enhancements.

Use Python Interpreter

A Python interpreter is responsible for running Python scripts, and it works on the Read-Eval-Print-Loop (REPL) environment. Although unconventional, you can specify the Python interpreter in the shebang line to allow a Python script to execute Bash script commands.

For example:

#!/usr/bin/env python

The env command locates the Python interpreter in the $PATH, and the OS uses it to execute the script.

For example:

1. Create a new script and paste the following lines:

#!/usr/bin/env python3
print('hello world')

2. Save the changes and make the script executable.

3. Run the script:

Running a script with the Python interpreter specified in the shebang line.

The Python interpreter interprets and executes the script.

Use Specific Version of Bash

Specify a version of the Bash interpreter in the shebang line to execute a script using that interpreter. Using a specific Bash version ensures compatibility with older systems that don't support newer Bash versions or if your script requires features available only in a specific Bash version.

For example:

#!/bin/bash-5.1

This shebang line specifies version 5.1 of the Bash interpreter to execute the script.

Use Different Shell Interpreter

Bash has several shell alternatives in Unix-like systems. The shebang line allows users to specify a different shell in their script. One such shell is the Korn shell (ksh), which offers better performance in script execution and has more programming features.

The following example shows how to specify the Korn shell in the shebang line:

#!/bin/ksh
# Korn shell script code here

The shebang line specifies the Korn shell (ksh) as the interpreter for executing the script.

Use Interpreted Language Other than Bash

An interpreted language is a programming language that is generally interpreted and doesn't require compilation before it is executed. In such languages, the instructions are not directly executed by the target machine. Instead, another program reads and executes them.

One such programming language is Perl, and you can specify it in the shebang line to use the Perl interpreter for script execution:

#!/usr/bin/env perl

The following example script is a hello world script executed using Perl:

1. Create a new script and paste the following lines:

#!/usr/bin/env perl
# Modules used
use strict;
use warnings;
# Print function
print("Hello World\n");

2. Make the script executable.

3. Run the script:

Running a script with the Perl interpreter specified in the shebang line.

In this example, the shebang line uses env to locate perl, and the OS uses it to execute the script. Replace perl with other interpreted languages like Ruby, Python, or PHP, depending on your requirements.

Use Shell Script as Configuration File

Shell scripts can serve as configuration files by specifying #!/bin/false as the interpreter. The interpreter prevents the script from being executed and causes it to exit with a non-zero status.

That way, the script can be used as a configuration file. Instead of executing the script, it can be sourced or included within another script or program. The variables and settings defined in the script can then be accessed and utilized by the calling script or program.

#!/bin/false
# Configuration parameters defined as shell variables

The shebang line #!/bin/false indicates that the script is not intended for execution as a standalone script. Instead, it serves as a configuration file where variables and settings can be defined. Thus, the script has no output, regardless of what it contains.

The variables defined in the script can be used to store values such as usernames, passwords, file paths, or any other settings specific to the application or script.

Use Shell Wrapper Script

A shell wrapper script is a script that embeds a command or utility and saves a set of parameters passed to that command. The purpose of using a shell wrapper is to simplify invoking a complex command line.

The syntax for using a shell wrapper script is:

#!/bin/bash
exec /path/to/actual/script.sh "$@"

This shebang line is used in a shell wrapper script that executes another script located at /path/to/actual/script.sh while passing any command-line arguments ("$@") to it. The line allows you to add functionality or pre-processing before invoking the main script.

The following example shows how to replace egrep in new GNU/Linux systems with a wrapper script named egrep:

#!/bin/bash
exec grep -E "$@"

Running egrep in such systems actually runs grep -E and forwards all the arguments.

Use Different Custom Interpreter or Command

Aside from all the interpreters mentioned above, the shebang line allows you to specify a custom interpreter or command you want to use to execute the script.

The syntax for specifying a custom interpreter or command in the shebang line is:

#!/[path/to/custom/interpreter]
# Code executed by the custom interpreter

Remember to place the shebang at the beginning of the script file, with no spaces or extra characters before it. The line informs the operating system how to execute the script when invoked.

How to Override the Interpreter

Linux allows you to override the interpreter set by the shebang line by specifying which shell you want to use when running a script. For example, if a script contains #!/bin/ksh in the shebang line, but you want to run it using the Bash shell, use the following syntax:

bash [script_name]

For example:

bash helloworld.sh
Overriding the interpreter specified in the shebang line.

The command runs the specified script using the Bash shell, regardless of which shell interpreter is specified in the shebang line. However, be careful when overriding the shell interpreter, as it may lead to the script malfunctioning or unexpected behavior.

Conclusion

This tutorial showed how to use the shebang line in Bash scripts to specify which shell interpreter or command the system should use to execute the script. The shebang line allows developers to create scripts and control which shell and command execute the script.

For more scripting tutorials, read our articles regarding writing a Bash script or learn to use the for loop in Bash scripts through hands-on examples.

Was this article helpful?
YesNo
Bosko Marijan
Having worked as an educator and content writer, combined with his lifelong passion for all things high-tech, Bosko strives to simplify intricate concepts and make them user-friendly. That has led him to technical writing at PhoenixNAP, where he continues his mission of spreading knowledge.
Next you should read
What Is the .bashrc File in Linux?
January 23, 2023

The .bashrc file holds all the configuration for the Bash shell. Learn how to configure the Bash shell using functions and aliases and create custom colors. Every shell should be unique.
Read more
Bash Single vs. Double Quotes: What's the Difference?
January 5, 2023

Single and double quotes are often used in Bash to instruct the shell how to interpret the input string. This tutorial clarifies the difference between the two quote types.
Read more
Bash String Comparison
September 22, 2022

This tutorial shows how to use the Bash shell in Linux to compare two strings in different ways. See examples for each comparison and create example scripts to learn to compare strings in Bash.
Read more
Bash Math Operations Explained
April 14, 2022

You can perform math and arithmetic operations in Bash directly. Although the functionalities are basic, the examples from this tutorial show how to maximize the use of math in Bash scripts.
Read more