Your first script - shebang and execute bit

Beginner · 12 min

Turn commands into a reusable script file: the #! line that names the interpreter, the execute permission, and why a script needs ./ to run.

Before thisPermissions and chmodThe PATH and how commands are foundCommand and arithmetic substitutionWord splitting and the order of expansion

Learn Linux TV · 17 min · from 5:03

Your first script - shebang and execute bit

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Learn Linux TVReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A script is a text file of commands. Bash reads and runs it top to bottom, exactly as if you had typed the lines.
  • The first line, `#!/usr/bin/env bash`, is the shebang. The kernel reads it to decide which program should interpret the file.
  • A file needs the execute bit (`chmod +x`) before you can run it by path. `bash file` works without it, because then Bash is the program being executed.
  • A bare command name is searched for in `PATH`, and the current directory is not in it, so you write `./script` or install it into a directory that is.
  • On macOS `/bin/bash` is 3.2 and `/bin/sh` is also Bash 3.2 in POSIX mode, while `#!/usr/bin/env bash` picks up whichever Bash comes first in `PATH`.

From command history to a file

Sooner or later you type the same three commands twice. Maybe you count log lines, filter the server errors, and report both. A shell is happy to run those lines from a file instead of from your fingertips. A script is exactly that: a plain text file of commands that Bash executes top to bottom.

This is the first version of the small tool this group builds, logsum. It uses the 200-line access.log fixture, where field 8 is the HTTP status.

#!/usr/bin/env bash
# logsum: how many requests, and how many server errors
total=$(wc -l < logs/access.log)
errors=$(awk '$8 >= 500' logs/access.log | wc -l)
echo "requests: $((total)) server errors: $((errors))"

Everything in it is a command from earlier lessons. The $((total)) wrapper strips the padding that macOS wc adds. ShellCheck reported nothing on this file.

Running it: the execute bit

The file exists but isn’t allowed to run yet:

$ ls -l logsum | cut -c1-10
-rw-r--r--
$ ./logsum
bash: ./logsum: Permission denied
$ chmod +x logsum
$ ls -l logsum | cut -c1-10
-rwxr-xr-x
$ ./logsum
requests: 200 server errors: 24

Permissions were covered in the chmod lesson. The point here: running a file by path requires the execute bit, because the operating system checks it before treating the file as a program. chmod +x adds it for the owner, group and others. There is a way around it: bash logsum worked on the file with or without the bit, because then the program being executed is bash, and logsum is just an argument it reads.

Why ./ and not just the name

$ logsum
bash: logsum: command not found
$ PATH="$PWD:$PATH" logsum
requests: 200 server errors: 24

A bare command name is searched for in PATH, and the current directory is deliberately not in it, since a stray file in a shared directory could otherwise hijack a common command name. ./logsum contains a slash, so Bash skips the search and runs that path. Putting the script in a directory that is on PATH, or adding its directory, makes the bare name work, as the second command shows.

The shebang line

When you run ./logsum, who interprets the file? Bash itself is not guessing. The kernel reads the first two bytes, and if they are #!, it launches the program named on that line and gives it the script as an argument. That line is the shebang. Here are three versions I ran, each printing the Bash version it ran under:

$ ./v1; ./v2; ./v3
bash 3.2.57(1)-release
bash 5.3.20(1)-release
sh: [3.2.57(1)-release]

v1 used #!/bin/bash, which on this Mac is Apple’s Bash 3.2. v2 used #!/usr/bin/env bash, which asks env to find bash along PATH, and my PATH had Homebrew’s Bash 5.3 first. v3 used #!/bin/sh, and it printed a Bash version, because on macOS /bin/sh is itself Bash 3.2 running in POSIX mode (/bin/sh --version confirmed it). On many Linux systems /bin/sh is dash, where the version variable would be empty, so a script that works under #!/bin/sh on a Mac can fail on Linux if it uses Bash features. Use #!/usr/bin/env bash when you want Bash and can’t predict where it lives. Use #!/bin/sh only for scripts written to be portable (the portability lesson covers that).

If the interpreter doesn’t exist, you get a clear error:

$ ./v4
bash: ./v4: /no/such/interpreter: bad interpreter: No such file or directory

I trimmed the harness path off the front of that message. And a file with no shebang, run as ./v5, still ran, interpreted by the shell I launched it from. That works, but it is the behaviour you want to avoid depending on.

Arguments and $0

A script receives arguments in numbered variables, with $# holding the count and $0 the name it was called by:

$ ./args.sh a "b c"
script: ./args.sh, first: a, count: 2

Quoting kept b c as a single argument. Later lessons build on this: getopts for options, and functions for reusable pieces.

About the video

Learn Linux TV’s “How To Write Bash Scripts In Linux - Complete Guide (Part 2 - Hello World)” is 17 minutes 24 seconds, uploaded in November 2022. I couldn’t read a transcript. The description’s time codes put the intro at 0:00, a shell explainer at 1:03, “How to turn Linux command(s) into a Bash Script” at 5:03, marking a script executable with chmod at 6:40, and running it at 8:32. A final chapter at 12:37 was cut off in the text I could read. The embed starts at 5:03 (303 seconds), skipping the shell explainer this roadmap already covers. The video is in English. The second view is You Suck at Programming’s long shebang video, which I judged by its title only.

Where this fits

A script that always exits quietly isn’t much help. Next: how a command reports success or failure, and how to chain commands on that signal in exit status and &&/|| lists.

Check yourself

  1. 01You created `backup.sh` and `./backup.sh` says `Permission denied`. What is missing?

    The execute permission. Run `chmod +x backup.sh`. Until then you can still run it as `bash backup.sh`, which only needs read permission.

  2. 02Why does `logsum` say `command not found` while `./logsum` works in the same directory?

    A bare name is looked up in the directories listed in `PATH`, and the current directory isn't one of them. `./` gives an explicit path, so no search happens.

  3. 03What is the practical difference between `#!/bin/bash` and `#!/usr/bin/env bash`?

    The first names one fixed interpreter, which on a stock Mac is Bash 3.2. The second asks `env` to find `bash` in `PATH`, so it picks up a newer Homebrew Bash when one is installed.

  4. 04What happens if a script has no shebang line at all?

    When run by path, the shell that started it interprets the file itself, so it works but depends on which shell you launched it from. Always include a shebang.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark