Shell Script · Shebang

Shell Scripting · Lesson 3

Shebang

Understand the role of shebang (#!) in shell scripts. Learn how interpreter path works in Linux. Difference between bash, sh and other interpreters. Best practices for portable scripts.

What is Shebang?

The shebang is the first line of a script that tells the operating system which interpreter should be used to execute the file.

It always starts with #! followed by the absolute path of the interpreter.

Why Shebang is Important

Interpreter Selection

It tells the OS which program should execute the script.

Direct Execution

Allows running scripts like normal commands using ./script.sh.

Portability

Helps scripts run consistently across different systems.

Common Shebang Examples

  • #!/bin/bash – Bash shell
  • #!/usr/bin/env bash – Portable bash
  • #!/bin/sh – POSIX shell
  • #!/usr/bin/python3 – Python script

Hands-on Examples

1. Basic Shebang Example

A simple shell script using bash as the interpreter.

terminal — bash
shebang
#!/bin/bash
echo "Hello from Bash script"

2. Using /usr/bin/env

This makes the script portable across systems where bash path may differ.

terminal — bash
shebang
#!/usr/bin/env bash
echo "Running with env bash"

3. Make Script Executable and Run

Give execute permission and run the script directly.

terminal — bash
shebang
chmod +x hello.sh
./hello.sh

4. Running Without Shebang

If a script has no shebang, you must specify the interpreter manually.

terminal — bash
shebang
bash hello.sh

Common Mistakes

Avoid These Errors

  • Adding spaces before #! in the first line.
  • Using wrong interpreter path.
  • Forgetting to make the script executable.
  • Using Windows line endings (CRLF).

Practice Task – Shebang Mastery

  • Create a script with #!/bin/bash.
  • Print your username and current date.
  • Make the script executable and run it.
  • Try running it with and without ./.

Next lesson: Variables in Shell Scripting