Step-by-Step Tutorial: How to Write a Bash Script

Updated

how to write bash linux

A bash script is a text file that starts with #!/usr/bin/env bash (or #!/bin/bash), is made executable with chmod +x script.sh, and runs as ./script.sh. The eleven steps below write one from an empty file.

Step 1: Create the script file

A script is a plain text file of commands, and the .sh ending is only a convention. This creates a one-line script and runs it by naming the interpreter, which needs neither a shebang line (step 2) nor execute permission (step 10):

$ printf '%s\n' 'echo "Hello from my first script"' > hello.sh
$ bash hello.sh
Hello from my first script

Step 2: Start with a shebang line

The first line, #! plus an interpreter, tells the system which program runs the file. #!/bin/bash always uses that path; #!/usr/bin/env bash uses the first bash on your PATH, which the bash manual calls a common idiom for finding bash when it is installed elsewhere. I recommend the env form for scripts you share. On this Mac, where Homebrew’s bash comes first in PATH, the two pick different shells (step 10 explains chmod +x):

$ type -a bash
bash is /opt/homebrew/bin/bash
bash is /bin/bash
$ printf '%s\n' '#!/bin/bash' 'echo "$BASH_VERSION"' > fixed.sh
$ printf '%s\n' '#!/usr/bin/env bash' 'echo "$BASH_VERSION"' > flexible.sh
$ chmod +x fixed.sh flexible.sh
$ ./fixed.sh
3.2.57(1)-release
$ ./flexible.sh
5.3.15(1)-release

Step 3: Add comments

A # at the start of a word begins a comment, and bash ignores the rest of the line:

#!/usr/bin/env bash
# comments.sh: this whole line is a comment.
echo "Hello"   # a trailing comment
$ bash comments.sh
Hello

Step 4: Use variables and quote them

Assign with name=value, with no spaces around the =, and read it back with $name. Quote every expansion, because word splitting applies to the results of unquoted parameter expansion, command substitution and arithmetic expansion, including a string built from several variables (concatenating strings in bash covers += and the quoting traps).

#!/usr/bin/env bash
# vars.sh: variables and quoting
name="Ada"
file="my report.txt"
echo "Hello, $name"
printf '%s\n' $file
printf '%s\n' "$file"
$ bash vars.sh
Hello, Ada
my
report.txt
my report.txt

printf '%s\n' prints one argument per line, so the unquoted $file arrives as two arguments. With spaces around the =, bash runs a command called name and prints name: command not found.

Step 5: Read command-line arguments

Inside the script, $1, $2 and so on hold the arguments, $# counts them, $0 is the script’s own name, and "$@" expands to every argument as a separate word. ${1:-World} supplies a default when $1 is unset or empty. Passing arguments to a shell script covers shift and getopts.

#!/usr/bin/env bash
# args.sh: read arguments
name="${1:-World}"
echo "Hello, $name (got $# arguments)"
for arg in "$@"; do
  echo "arg: $arg"
done
$ bash args.sh
Hello, World (got 0 arguments)
$ bash args.sh Ada "Grace Hopper"
Hello, Ada (got 2 arguments)
arg: Ada
arg: Grace Hopper

Step 6: Test conditions with if and [ ]

if branches on a command’s exit status. [ is itself a command, a synonym for test, so it needs a space after [ and before ], and the variables inside should be quoted. -f tests for a regular file, -d for a directory, -z for an empty string, and -eq, -lt and -ge compare integers. A missing space is the classic failure; see common mistakes below.

#!/usr/bin/env bash
# check.sh: test a path
path="$1"
if [ -z "$path" ]; then
  echo "usage: check.sh PATH"
elif [ -d "$path" ]; then
  echo "$path is a directory"
elif [ -f "$path" ]; then
  echo "$path is a regular file"
else
  echo "$path does not exist"
fi
$ bash check.sh
usage: check.sh PATH
$ bash check.sh .
. is a directory
$ bash check.sh hello.sh
hello.sh is a regular file
$ bash check.sh nothing
nothing does not exist

Step 7: Loop over files and lines

A for loop runs its body once per item, and a glob such as *.txt expands to the matching file names. Quote "$f", because names can contain spaces. With no match, bash leaves the pattern as literal text, so a directory with no .txt files prints found: *.txt unless the [ -e "$f" ] || continue guard skips it:

#!/usr/bin/env bash
# loop.sh: loop over .txt files
for f in *.txt; do
  [ -e "$f" ] || continue
  echo "found: $f"
done
$ touch a.txt "my notes.txt"
$ bash loop.sh
found: a.txt
found: my notes.txt

To read a file line by line, use while read. IFS= keeps leading and trailing spaces and -r keeps backslashes; plain read strips the spaces and treats \ as an escape. A for ... in or while loop needs a ; or a newline before do and before done.

#!/usr/bin/env bash
# lines.sh: read names.txt line by line
while IFS= read -r line; do
  echo "line: [$line]"
done < names.txt
$ printf '%s\n' 'Ada Lovelace' '  Grace Hopper' 'back\slash' > names.txt
$ bash lines.sh
line: [Ada Lovelace]
line: [  Grace Hopper]
line: [back\slash]

Step 8: Group commands into functions

Define a function with name() { ... } before the line that calls it; calling it earlier gives greet: command not found. Inside, $1, $2 and $# are the function’s own arguments. Variables are shared with the caller unless declared local; without it, the last line below would print name is still Grace Hopper.

#!/usr/bin/env bash
# func.sh: functions and local variables
greet() {
  local name="$1"
  echo "Hello, $name"
}

name="outer"
greet "Ada"
greet "Grace Hopper"
echo "name is still $name"
$ bash func.sh
Hello, Ada
Hello, Grace Hopper
name is still outer

Step 9: Handle exit codes and set -euo pipefail

Every command ends with an exit status: 0 means success and anything else means failure. $? holds the last status and exit N ends your script with status N. A bare exit returns the last command’s status, as the bash exit command shows.

$ [ -f missing.txt ]; echo "status: $?"
status: 1
$ bash -c 'exit 7'; echo "status: $?"
status: 7

Many scripts begin with set -euo pipefail: -e exits when a command fails, -u treats an unset variable as an error, and -o pipefail makes a pipeline fail when any command in it fails. This one-liner stops at false:

$ bash -c 'set -euo pipefail; echo before; false; echo after'; echo "status: $?"
before
status: 1

It has caveats, listed in the manual’s description of set. -e is ignored in conditions: the shell does not exit when the failing command is part of an if test, a while or until condition, a && or || list (except its last command) or a ! pipeline, and a function called from such a context runs with -e ignored. Here check keeps going after false:

#!/usr/bin/env bash
# caveat.sh: -e is ignored inside a function called from if
set -e

check() {
  false
  echo "check kept going"
}

if check; then
  echo "check passed"
fi
$ bash caveat.sh
check kept going
check passed

Without pipefail, the last command hides an earlier failure in a pipeline:

$ bash -c 'false | true; echo "default: $?"'
default: 0
$ bash -c 'set -o pipefail; false | true; echo "pipefail: $?"'
pipefail: 1

On macOS’s bash 3.2.57, -u also rejects an empty array ("${files[@]}" fails with files[@]: unbound variable; 5.3.15 accepts it), and -e ends the script when a plain grep finds no match.

Step 10: Make the script executable and run it

chmod +x turns on the execute bit, and ./hello.sh then runs the script through its shebang line:

$ printf '%s\n' '#!/usr/bin/env bash' 'echo "Hello from $0"' > hello.sh
$ chmod +x hello.sh
$ ./hello.sh
Hello from ./hello.sh

Before the chmod, ./hello.sh fails with Permission denied (status 126), although bash hello.sh works. A bare hello.sh fails with command not found (status 127) because the current directory is normally not on PATH. For sourcing, CRLF line endings and cron, see how to run a bash script.

Step 11: Debug with bash -x and ShellCheck

bash -x script.sh prints each command to standard error, after expansion and with a + prefix, just before it runs. bash -n script.sh reads the script and reports syntax errors without running it.

#!/usr/bin/env bash
# debug.sh: a script to trace
count=2
total=$((count * 21))
echo "total: $total"
$ bash -x debug.sh
+ count=2
+ total=42
+ echo 'total: 42'
total: 42

ShellCheck warns about mistakes such as unquoted variables without running the script. Paste a script into the website, or install it with brew install shellcheck or sudo apt install shellcheck. This is ShellCheck 0.11.0 on a script that forgets the quotes:

#!/usr/bin/env bash
# unquoted.sh: forgets the quotes
file="my report.txt"
cat $file
$ shellcheck unquoted.sh

In unquoted.sh line 4:
cat $file
    ^---^ SC2086 (info): Double quote to prevent globbing and word splitting.

Did you mean:
cat "$file"

For more information:
  https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...

Common mistakes: missing separators and [ spacing

A loop with no separator before done

Copy this loop and run it, and bash refuses to execute it:

$ bash -c 'for i in 1 2 3; do echo "Number $i" done'
bash: -c: line 1: syntax error: unexpected end of file

That is the 3.2.57 wording; 5.3.15 says line 2 and ends it with from `for' command on line 1. Nothing separates echo "Number $i" from done, and bash recognizes done as a reserved word only as the first word of a command, so here it is one more argument to echo and the loop never closes. A while loop written the same way has the identical problem, plus a second instance of it between count=1 and while:

$ bash -c 'count=1 while [ $count -le 3 ]; do echo "Count $count" count=$((count + 1)) done'
bash: -c: line 1: syntax error near unexpected token `do'

That is the first line of 5.3.15’s output; both versions add a second line quoting the command, and 3.2.57 says line 0.

The fix: a separator before every keyword

Give do and done their own statement, either with a newline or a semicolon:

for i in 1 2 3; do
  echo "Number $i"
done

or, on one line, with a ; before done too:

for i in 1 2 3; do echo "Number $i"; done

Both print Number 1, Number 2, Number 3 and exit 0. The corrected while loop:

count=1
while [ "$count" -le 3 ]; do
  echo "Count $count"
  count=$((count + 1))
done

count=1 needs its own line too: after an assignment on the same line, bash does not treat while as a keyword.

Missing spaces around [ and ]

[ is not syntax: it is a command (a synonym for test), and like any command its arguments must be whitespace-separated. Squeeze the space out and it breaks the same way a missing space in any other command would:

$ bash -c 'if [$1 -eq 10 ]; then echo hi; fi'
bash: line 0: [: -eq: unary operator expected

That is 3.2.57’s output; 5.3.15 says line 1. With $1 empty, [$1 becomes the single word [, so bash runs [ -eq 10 ]. Write if [ "$1" -eq 10 ]; then, with spaces inside the brackets and the variable quoted so an empty or multi-word value doesn’t collapse the argument count.

The numeric tests accept integers only, so [ 1.5 -gt 1 ] is an error, not a comparison (3.2.57 says integer expression expected, 5.3.15 says integer expected). Compare decimals with awk; parsing decimals with awk and cut shows how.

Bash script template to copy

A skeleton to start from: a shebang, strict mode, a usage function that prints to standard error and exits with 2 (the status bash’s own builtins return for incorrect usage), and a main function that receives the arguments:

#!/usr/bin/env bash
# check-files.sh: report which of the given files exist.
set -euo pipefail

usage() {
  echo "usage: ${0##*/} FILE..." >&2
  exit 2
}

main() {
  [ "$#" -ge 1 ] || usage
  local file status=0
  for file in "$@"; do
    if [ -f "$file" ]; then
      echo "ok: $file"
    else
      echo "missing: $file" >&2
      status=1
    fi
  done
  return "$status"
}

main "$@"

It exits 1 when any file is missing:

$ chmod +x check-files.sh
$ ./check-files.sh hello.sh nothing "my notes.txt"; echo "status: $?"
ok: hello.sh
missing: nothing
ok: my notes.txt
status: 1
$ ./check-files.sh; echo "status: $?"
usage: check-files.sh FILE...
status: 2

I ran every example on this page on macOS 26.6, with the system /bin/bash 3.2.57 and Homebrew’s bash 5.3.15 (plus ShellCheck 0.11.0 for step 11), and I did not test Linux distributions, dash or zsh.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.