Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 95 ยท Shell Scripting

Writing Your First Script

Write and run your first Bash script: the shebang line, bash script.sh versus ./script, chmod +x, structure, comments, exit status, and bash versus sh.

A shell script is a text file of commands. Everything you have typed so far, ls, grep, pipes, redirections, can be saved in a file and run again whenever you like. That is the whole idea, and it is one of the most useful skills on Linux: the boring task you did by hand three times becomes a command you run in one second.

In this lesson you will write a script, learn what the mysterious first line #!/usr/bin/env bash does, run a script in three different ways, give it permission to execute, and meet exit status, the way every script tells its caller whether it worked. You will also see how our in-browser editor runs your code, so you can predict what each example does.

What a script is

Open a terminal, type echo hello, press Enter: the shell reads the line and runs it. A script is the same thing with the lines stored in a file instead of typed. The shell reads them one at a time, from top to bottom, and executes each.

Bash Your first script, written and run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

How our editor works. The code you see in a bash example is itself saved as a script (named main.sh) and run by a real Bash 5 on Linux. Each run happens in a fresh temporary folder, which is why the examples start with mkdir demo && cd demo. A script written by an example (like greet.sh above) is a second script that the first one creates and runs.

A script can contain anything you could type interactively: pipes, redirections, loops, functions. Later lessons add variables, tests and loops (Variables, Conditionals, Loops). Right now we focus on the file itself.

The shebang line

The first line of most scripts starts with the two characters #!, called shebang (or hash-bang), followed by the path of the program that should run the script:

Terminal
#!/usr/bin/env bash
echo "I am a script"

When you run a script as a program (./greet.sh), the kernel looks at the first two bytes. If they are #!, it starts the named interpreter and passes it the script's path. That is why a file of shell commands, a file of Python code and a file of Perl code can all be run the same way: the shebang says who reads them.

TEXT
   ./greet.sh                kernel reads first line:  #!/usr/bin/env bash
        |                                                      |
        +--> kernel starts:  /usr/bin/env bash ./greet.sh <----+
                                      |
                        env searches PATH, finds bash
                                      |
                           bash reads greet.sh, runs it

Three common forms:

Shebang Meaning
#!/bin/bash Use exactly this Bash. It works on nearly every Linux system, but not on systems where Bash lives elsewhere (some BSDs, NixOS, macOS with a newer Homebrew Bash)
#!/usr/bin/env bash Ask env to find bash on the user's PATH. More portable, and picks the Bash the user prefers
#!/bin/sh A POSIX shell. Bash-only features may fail (see the end of this lesson)

For scripts that use Bash features, #!/usr/bin/env bash is the usual recommendation. The shebang must be the very first line, with nothing before it, not even a blank line.

Without a shebang, ./script still works in an interactive shell (Bash then runs the file with itself), but the result depends on who started it. Always write one.

Three ways to run a script

Bash bash script.sh versus ./script.sh

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Look at what happened:

  1. bash hello.sh: you start Bash yourself and tell it which file to read. The execute permission is irrelevant (reading is enough) and the shebang line is just a comment. This is the easy way to test.
  2. ./hello.sh without permission fails with Permission denied and status 126, the shell's code for "found, but cannot be executed".
  3. chmod +x hello.sh adds the execute bit. Now ./hello.sh works, and the kernel uses the shebang.

Note the ./. A bare hello.sh is searched for in the directories of PATH and not in the current directory (a safety feature, so a stray file cannot hijack a command name). ./ means "this folder" and makes the path explicit. To run a script by name from anywhere, put it in a directory that is on PATH, such as ~/bin or /usr/local/bin. File permissions are explained in File Permissions and Ownership.

Bash Putting a script on the PATH

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The "not found" error has status 127. Remember the pair: 126 means "exists but cannot run", 127 means "does not exist (or is not on the PATH)".

Script structure

A tidy script has a recognizable shape. Nothing here is required, but it is what experienced authors do:

Terminal
#!/usr/bin/env bash
# backup-notes.sh - copy the notes folder to a dated archive.
# Usage: backup-notes.sh SOURCE_DIR

set -euo pipefail          # stop on errors (see the lesson on exit codes)

main() {
  local source_dir=$1
  echo "Backing up $source_dir"
}

main "$@"
  • Line 1: the shebang.
  • A header comment: what the script does and how to call it.
  • Settings: set -euo pipefail is common, but it has pitfalls. Exit Codes, set -e and Error Handling covers them, so we do not rely on it blindly yet.
  • Functions (Functions) hold the logic, and a final line such as main "$@" starts it. This keeps variables local and the script readable.

Comments

Anything after a # up to the end of the line is a comment. The shell ignores it. Good comments explain why, not what the next line plainly says.

Bash Comments and line continuation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Other shebangs and multi-line comments

The shebang is not limited to shells. Any program that reads a file as its first argument works:

Shebang Runs the file with
#!/usr/bin/env python3 Python 3
#!/usr/bin/perl -T Perl in taint mode (options after the path are passed along)
#!/usr/bin/env ruby Ruby
#!/usr/bin/php PHP command-line interpreter
#!/bin/csh The C shell
#!/usr/bin/awk -f awk, reading the program from the file

The kernel passes everything after the interpreter path as one argument, so #!/usr/bin/env python3 -O fails on Linux; set complicated options inside the script instead.

Bash has no block-comment syntax, only # to the end of the line. A well-known trick is to feed the block to the do-nothing command : as a quoted here-document, which is handy to disable a block of code for a moment:

Bash Disabling a block with a here-document

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The quotes around 'DISABLED' matter: they stop the shell from expanding $(...) inside the block. Common mistakes with comments are commenting too much (a comment that repeats the code gets out of date), and forgetting that # inside quotes or in the middle of a word is plain text.

Exit status

Every command finishes with a number between 0 and 255, its exit status. The convention, used by every program on the system:

  • 0 means success.
  • Anything else means some kind of failure; the number says which kind.

The shell stores the status of the last command in the special variable $?. A script's own exit status is the status of the last command it ran, or the number given to exit.

Bash Reading and setting exit status

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

exit N ends the script immediately with status N. Without an argument, exit uses the status of the last command. Conventions worth following in your own scripts:

Status Meaning
0 Success
1 General failure
2 Wrong usage (bad arguments); also what Bash itself uses for syntax errors
126 Found but not executable
127 Command not found
128 + N Killed by signal N (so 130 is Ctrl-C, 143 is SIGTERM)

Other programs, and your own if and &&, use this number to decide what happens next. Write scripts so that success is 0 and failure is non-zero, and callers can chain them with && and || as with any command. The next lessons make heavy use of it, and Exit Codes, set -e and Error Handling goes deep.

Checking a script without running it

bash -n script.sh parses a script and reports syntax errors without executing anything. It is a cheap sanity check before you run something that deletes files:

Bash bash -n finds syntax errors safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

bash -n finds only errors in the grammar. It cannot find a misspelled command or a wrong filename; those only appear at run time. For a deeper toolbox see Debugging Shell Scripts.

bash versus sh

On many systems /bin/sh is not Bash at all. On Debian and Ubuntu it is dash, a small, fast shell that implements only the POSIX standard. Features that are Bash extensions, called bashisms, fail there: arrays, [[ ]], ${var^^}, <( ), {1..5}, and more.

Bash The same line under bash and sh

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The error shows Syntax error: "(" unexpected with status 2. The rules to remember:

  • Start with #!/usr/bin/env bash and use Bash features freely when you control the environment. This tutorial teaches Bash.
  • Write #!/bin/sh only when you really restrict yourself to POSIX features, for example in installers, Dockerfiles for small images or boot scripts. POSIX sh, Portability and Compatibility shows how.
  • The shebang beats the file name. A file called run.sh with #!/usr/bin/env python3 is a Python script. The extension .sh is only a convention. Commands in PATH typically have no extension at all.
  • Running sh script or bash script overrides the shebang, because you choose the interpreter yourself.

A script that does something

Let us finish with a small, complete script that follows the conventions above: a header comment, a function, an argument check, output on the right streams and a meaningful exit status.

Bash A complete small script

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The script keeps normal results on stdout and complaints on stderr, uses status 2 for wrong usage and 1 for a partial failure, and quotes every variable. Those habits make it a good citizen in pipelines. Do not worry yet about syntax such as ${0##*/} or for; they are explained in Parameter Expansion and String Handling and Loops.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the first line #!/usr/bin/env bash do?

    When you execute the file (./script), the kernel reads the shebang and starts the named interpreter with the script path. It does not set the execute permission; chmod +x does that.
  2. 2. You run ./deploy.sh and see Permission denied. What is the most likely fix?

    The file lacks the execute permission. Either add it with chmod +x or run it through the interpreter: bash deploy.sh needs only read permission.
  3. 3. Which exit status means that a command was not found?

    127 is the shell's code for command not found. 126 means the command was found but is not executable, and 0 means success.
  4. 4. Why do you type ./script.sh instead of just script.sh for a file in the current folder?

    Command names without a slash are searched for in the directories of PATH. ./ gives an explicit path, so no PATH search happens.
  5. 5. A script starting with #!/bin/sh uses an array: list=(a b c). On a system where /bin/sh is dash, what happens?

    dash implements only the POSIX standard. Arrays are a bashism, so dash stops with a syntax error.

Summary

  • A script is a text file of commands that the shell runs from top to bottom.
  • The first line, the shebang (#!/usr/bin/env bash), names the interpreter the kernel should start when the file is executed directly.
  • Run a script with bash script.sh (no permission needed) or ./script.sh (needs chmod +x). A bare name is looked up in PATH, not in the current folder.
  • Status 0 is success; non-zero is failure. 126 means not executable, 127 means not found, 128+N means killed by a signal.
  • exit N ends the script with status N; the status of the last command is the default. Print results on stdout and errors on stderr.
  • bash -n script.sh checks the syntax without running anything.
  • /bin/sh may be dash: use #!/usr/bin/env bash for Bash features and #!/bin/sh only for plain POSIX scripts.

Next: Variables and Environment Variables