Understanding the Shebang (#!/usr/bin/env bash)

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 26 of 205

The first line of almost every Bash script looks like this:

#!/usr/bin/env bash

This line is called the shebang (also written hashbang, from the two characters # and !). It is a message from the script to the operating system: "when someone runs this file as a program, use this interpreter to read it." Without it, the system has no reliable way to know whether a text file contains Bash, Python, Perl or something else. In this lesson you will learn how the system uses the line, what each part means, and which of the two common forms to choose.

Understanding the Concept

A script is only a text file. A text file cannot run by itself; some program has to read its lines and carry them out. That program is the interpreter. For a Bash script the interpreter is bash, for a Python script it is python3, and so on.

When you type ./hello.sh, you do not name an interpreter, so the system needs another way to find out which one to use. The answer is the shebang line. It must be the very first line of the file, and the first two bytes of the file must be exactly # followed by !. You can confirm this on any script:

head -c 2 hello.sh

Output:

#!

Everything after those two characters, up to the end of the line, tells the system which program to start.

How It Works

The work is done by the operating system's kernel, not by Bash. The steps are:

  1. You type ./hello.sh and press Enter. Bash asks the kernel to execute the file (the system call is named execve).
  2. The kernel opens the file and reads its first bytes. If they are #!, the kernel knows this is a script and not a compiled program.
  3. The kernel reads the rest of the first line. The first word is the path of the interpreter, and anything after it is treated as one optional argument.
  4. The kernel starts the interpreter and passes it the path of the script as an argument, followed by any arguments you typed.

So the system turns your command into something like this:

/usr/bin/env bash ./hello.sh arg1 arg2

Because the interpreter receives the script's path, it can open the file and read its lines. Inside the script, $0 holds that path and $1, $2 hold the arguments you typed:

#!/usr/bin/env bash
echo "args: $#  first=$1"

Saved as ar.sh and made executable, running it gives:

./ar.sh one two
args: 2  first=one

For the interpreter, the shebang line is simply a comment, because it begins with #. Bash ignores it when it reads the file, which is why the line does no harm.

Syntax

#!interpreter-path [optional-argument]
  • #! are the first two characters of the file.
  • interpreter-path is the path to the program that should run the script. It must be a full path, because the kernel does not search PATH.
  • A single optional argument may follow, separated by spaces. Everything after the first space is passed as one string.
  • A space between #! and the path is allowed by most systems (#! /bin/bash), but the form without a space is the usual one.
  • The line must end with a normal line feed. Windows line endings break it, as shown later.

The Two Common Forms

Two forms of the shebang are widely used for Bash.

A fixed path:

#!/bin/bash

This tells the kernel to run exactly /bin/bash. It is short and predictable. Its weakness is that Bash does not live at /bin/bash on every system. On some systems it is installed in another directory, and on macOS the file at /bin/bash is an old version (3.2), while a newer one installed with Homebrew lives elsewhere.

Search with env:

#!/usr/bin/env bash

Here the interpreter is /usr/bin/env, a small program whose job is to run another program found by searching the directories in PATH. The kernel starts env and gives it bash and the script path. Then env looks for bash in PATH and starts the first one it finds. The path /usr/bin/env exists on virtually every Linux and macOS system, so the line works where Bash is installed in an unusual place.

You can see which Bash env would pick with:

command -v bash

Output (the path depends on the system):

/usr/bin/bash

The env form follows the user's PATH. If a person has installed a newer Bash and placed it first in PATH, the script uses that one. This flexibility is also its trade-off: the script runs whichever bash comes first. To show this, this test puts a fake bash at the front of PATH:

mkdir -p fake
printf '#!/bin/sh\necho "fake bash ran"\n' > fake/bash
chmod +x fake/bash
PATH="$PWD/fake:$PATH" ./hello.sh

Output:

fake bash ran

The script was started by the program named bash that appeared first in PATH. In a normal setup that is the real Bash, but the experiment shows why a script that must be tightly controlled, such as one that runs with administrator rights, is safer with a fixed path.

Basic Example

Create a file named version.sh with this content:

#!/usr/bin/env bash
echo "Running under: $BASH_VERSION"

Make it executable and run it:

chmod +x version.sh
./version.sh

Output (your version number will differ):

Running under: 5.2.21(1)-release

BASH_VERSION is a variable that Bash itself sets, so seeing a value proves that the script was handed to Bash.

Understanding the Example

  1. ./version.sh starts the kernel's script handling.
  2. The kernel sees #!/usr/bin/env bash, so it starts /usr/bin/env with the arguments bash and ./version.sh.
  3. env searches PATH, finds bash, and starts it with ./version.sh as its argument.
  4. Bash reads the file. The first line is a comment. The second line prints the message, with $BASH_VERSION replaced by the version number.

The Shebang Selects the Interpreter

Because the shebang chooses the program, it also decides which language rules apply. The same file text can behave differently under a different interpreter. Here is a script that declares sh instead of Bash but uses Bash-only syntax:

#!/bin/sh
echo "BASH_VERSION=[$BASH_VERSION]"
if [[ 5 -gt 3 ]]; then echo "bigger"; fi

Saved as shx.sh and made executable, running it directly on a system where /bin/sh is Dash (Debian and Ubuntu) gives:

./shx.sh
BASH_VERSION=[]
./shx.sh: 3: [[: not found

Dash has no [[ ... ]] and does not set BASH_VERSION. The shebang sent the script to the wrong interpreter. On a system where /bin/sh is a link to Bash, the same script could behave differently, which is why a Bash script should name Bash.

Now run the same file by naming the interpreter yourself:

bash shx.sh
BASH_VERSION=[5.2.21(1)-release]
bigger

When you run bash shx.sh, the shebang is ignored. You chose the interpreter on the command line, and the first line is just a comment. This is an important rule: the shebang matters only when the file is executed directly. The next two lessons explain how to make a file executable and how to run a script in different ways.

Using the Shebang with Other Languages

The shebang is not specific to Bash. Any interpreter works, which is why the line is the standard way to make scripts in many languages directly runnable:

#!/usr/bin/env python3
print("Hello from Python")

Saved as p.py and made executable, ./p.py prints:

Hello from Python

The same idea works for Perl, Ruby, Node.js and any other language that reads a program from a file.

Passing an Option in the Shebang

Sometimes a script should always run with an option, for example Bash's -x, which prints each command as it runs. With a fixed path this works directly:

#!/bin/bash -x
echo hi

Output:

+ echo hi
hi

The lines starting with + are the trace that -x produces. With env, the same attempt fails on Linux, because everything after the first space is passed as one argument. env then looks for a program named bash -x, which does not exist:

#!/usr/bin/env bash -x
echo hi

Output:

/usr/bin/env: 'bash -x': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines

The message suggests the solution: the -S option of env means "split this string into separate arguments".

#!/usr/bin/env -S bash -x
echo hi

Output:

+ echo hi
hi

The -S option exists in GNU env (version 8.30 and later), and also in the env of macOS and FreeBSD. On older systems it may be missing. If you need to be sure, set the option inside the script instead, with the set -x command, which a later lesson explains.

Messages You May See

A broken shebang line produces recognizable errors. Each of these was produced with a one-line script.

The interpreter named by env is not installed:

#!/usr/bin/env nosuchprog
echo hi
/usr/bin/env: 'nosuchprog': No such file or directory

The exit status is 127.

A fixed path that does not exist (the script below is saved as m.sh):

#!/no/such/bash
echo hi
bash: ./m.sh: cannot execute: required file not found

The exit status is again 127. The file itself exists, which is why the wording says that a required file is missing: it is the interpreter. Older systems print bad interpreter: No such file or directory.

Windows line endings:

A file saved with Windows line endings ends each line with a carriage return and a line feed. The shebang then names the program bash followed by an invisible carriage return, and the system cannot find it:

/usr/bin/env: 'bash\r': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines

The fix is to save the file with Unix (LF) line endings.

What Happens Without a Correct Shebang

Two cases look similar but behave differently:

  • If the line is missing, or does not start with #! in the first two bytes (for example a space comes first), the kernel cannot use it. When you run the file from Bash, Bash falls back to running the file with itself. This works on the surface, but it depends on which program started the file.
  • Only the first line counts. A second line such as #!/bin/zsh further down is an ordinary comment:
#!/usr/bin/env bash
# not a shebang
#!/bin/zsh
echo "BASH_VERSION=$BASH_VERSION"

The script runs under Bash, and the later #! line is ignored, because the kernel read only line one.

Practical Applications

A shebang makes a script behave like a normal command. A small tool that reports disk usage for a directory, with no extension, can sit in a folder that is listed in PATH:

#!/usr/bin/env bash
# dirsize - print the total size of a directory.
target=${1:-.}
du -sh "$target"

Because of the shebang, the user does not need to know that the tool is a Bash script. They type dirsize ~/Documents, and the system starts Bash behind the scenes. The same approach is used for scripts written in other languages, so users can run a tool without knowing which language it is written in.

To check the shebang of any script, print its first line:

head -n 1 dirsize
#!/usr/bin/env bash

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Understanding the Shebang (#!/usr/bin/env bash) and get answers drawn from it.

Signed-in readers only.