Software & OS

Bash Script Basics: Write, Run and Debug Your First Bash Script

A bash script is a plain text file of shell commands that starts with a shebang line such as #!/usr/bin/env bash. Make it executable with chmod +x script.sh and run it with ./script.sh, or run it without the permission change as bash script.sh.

#!/usr/bin/env bash
set -euo pipefail

name="${1:-world}"
echo "Hello, $name"
chmod +x hello.sh
./hello.sh          # Hello, world
./hello.sh alex     # Hello, alex

Everything below builds on these few lines. The outputs shown are real, from bash 5.1 on Ubuntu (WSL) and bash 5.2 in Git Bash.

The shebang line: #!/usr/bin/env bash vs #!/bin/bash

When you run ./hello.sh, the kernel reads the first line. If it starts with #!, the rest of that line names the interpreter that should run the file (this is how execve handles "interpreter scripts").

  • #!/bin/bash runs bash from a fixed path. That path exists on almost every Linux system.
  • #!/usr/bin/env bash looks bash up in your PATH. Use this when bash may live elsewhere, as on macOS with a newer bash from Homebrew, or on FreeBSD.

Don't write #!/bin/sh for a script that uses bash features. On Ubuntu /bin/sh is a link to dash, and a bash array fails there:

$ sh arr.sh
arr.sh: 2: Syntax error: "(" unexpected

The same file run with bash arr.sh works.

Run a bash script: ./script.sh vs bash script.sh

A new file isn't executable, so ./hello.sh fails:

bash: ./hello.sh: Permission denied

chmod +x hello.sh adds the execute bit (see Linux file permissions and chmod for what that changes). Alternatively, bash hello.sh runs the file without needing the execute bit, and ignores the shebang.

The ./ matters. Typing just hello.sh makes bash search your PATH, which doesn't include the current directory:

hello.sh: command not found

Variables and quoting

name="alex"           # no spaces around =
greeting="Hello, $name"
echo "$greeting"

Spaces around = are the most common first error. name = "alex" makes bash run a command called name with arguments = and alex:

t.sh: line 1: name: command not found

Quote every variable expansion: "$file", not $file. Unquoted, bash splits the value on spaces. With file="my notes.txt":

if [ -f $file ]; then echo "exists"; fi
# t3.sh: line 5: [: my: binary operator expected

With quotes, [ -f "$file" ] sees one argument and works. Use single quotes when you want no expansion at all: echo '$HOME' prints $HOME literally.

Command substitution stores a command's output in a variable:

today=$(date +%Y-%m-%d)
count=$(find . -type f | wc -l)

Script arguments: $1, $#, "$@"

VariableMeaning
$0The script's name as it was called
$1, $2 …First, second … argument
$#Number of arguments
"$@"All arguments, each kept as a separate word
$?Exit status of the last command
${1:-default}$1 if set and non-empty, otherwise default

Always loop over "$@" in quotes. This script prints each argument both ways:

for arg in "$@"; do echo "[$arg]"; done
for arg in $*; do echo "<$arg>"; done

Run as bash args.sh "my file.txt" two:

[my file.txt]
[two]
<my>
<file.txt>
<two>

The unquoted version split one filename into two.

if statements and tests

if [ -f "$file" ]; then
  echo "file exists"
elif [ -d "$file" ]; then
  echo "it's a directory"
else
  echo "not found"
fi

The spaces inside [ ... ] are required, because [ is a command and its parts are arguments. Common tests:

  • Files: -f regular file, -d directory, -e exists, -x executable.
  • Strings: "$a" = "$b", "$a" != "$b", -z "$a" (empty), -n "$a" (not empty).
  • Numbers: -eq, -ne, -lt, -le, -gt, -ge. [ "$count" -gt 2 ] compares numbers; > inside [ ] would redirect output to a file named 2.

Bash also has [[ ... ]], which doesn't word-split its contents and supports pattern matching such as [[ $file == *.log ]]. It's bash-only, so it fails under dash.

Loops

# Over files
for f in *.log; do
  echo "processing $f"
done

# Over a range of numbers
for i in {1..5}; do echo "$i"; done

# While a condition holds
i=0
while [ "$i" -lt 3 ]; do
  i=$((i + 1))
done
echo "i=$i"          # i=3

# Over lines of a file
while IFS= read -r line; do
  echo "line: $line"
done < input.txt

$(( )) does integer arithmetic. In the file loop, IFS= keeps leading spaces and -r stops backslashes being treated as escapes.

Functions

greet() {
  local who="$1"
  echo "hi $who"
}

greet alex           # hi alex

Functions take arguments the same way scripts do ($1, "$@"). local keeps a variable from leaking into the rest of the script. A function "returns" data by printing it; capture it with result=$(greet alex). The return keyword sets only the exit status, a number from 0 to 255.

Exit codes

Every command exits with a status: 0 for success, anything else for failure. if, && and || all act on this number. grep exits 1 when it finds nothing; false always exits 1:

grep -q "pattern" file.txt || echo "not found, grep exit: $?"
false; echo "after false: $?"      # after false: 1

Your script should do the same: exit 0 on success, a non-zero code on failure, and error messages on standard error with >&2, so other scripts and cron jobs can tell when it failed.

set -euo pipefail: fail fast instead of carrying on

By default bash keeps going after a failed command, which is how a script that failed to cd ends up deleting files in the wrong directory. Put this under the shebang:

set -euo pipefail
  • -e: exit immediately when a command fails.
  • -u: treat an unset variable as an error. Output: t2.sh: line 3: undefined_var: unbound variable and exit status 1, instead of silently using an empty string.
  • -o pipefail: a pipeline fails if any command in it fails, not only the last one.

set -e has exceptions you need to know. A failing command used as an if condition, or on the left of || or &&, does not stop the script. And it can stop a script you didn't expect. This one exits at line 5, because grep -c prints 0 and exits 1 when there are no matches:

set -e
if grep -q zzz missing.txt 2>/dev/null; then echo found; fi
echo "still running after if-test"
grep -q zzz /dev/null || echo "handled with ||"
count=$(grep -c zzz /dev/null)
echo "never printed: $count"

Output: still running after if-test, then handled with ||, then the script exits with status 1. Append || true to commands where a non-zero exit is normal.

A complete small script

#!/usr/bin/env bash
set -euo pipefail

if [ $# -lt 1 ]; then
  echo "usage: $0 <directory>" >&2
  exit 2
fi

dir="$1"
if [ ! -d "$dir" ]; then
  echo "error: $dir is not a directory" >&2
  exit 1
fi

count=$(find "$dir" -type f | wc -l)
echo "$dir contains $count files"

Real runs:

$ bash safe.sh
usage: safe.sh <directory>        (exit status 2)
$ bash safe.sh nope
error: nope is not a directory    (exit status 1)
$ bash safe.sh demo
demo contains 2 files             (exit status 0)

It checks its arguments, writes errors to stderr, uses distinct exit codes and quotes every variable. For the commands you'll put inside scripts like this, see basic Linux commands and grep examples.

If your script still fails

  • /bin/bash^M: bad interpreter: No such file or directory: the file has Windows CRLF line endings. Bash also reports errors like cd: $'/tmp\r': No such file or directory. Convert with sed -i 's/\r$//' script.sh (or dos2unix), and set your editor to save with LF.
  • It works in your terminal but not from cron: cron runs with a minimal PATH and a different working directory. Use absolute paths, or set PATH at the top of the script.
  • You can't see what's happening: run bash -x script.sh. Each command is printed with variables expanded, for example + echo 'hi alex', before it runs.

Frequently asked questions

What is the difference between sh and bash scripts?
sh is the POSIX shell language; bash is a superset with extras such as arrays, [[ ]] tests and brace expansion. On Debian and Ubuntu, /bin/sh is dash, not bash, so running a bash script with sh script.sh can fail with errors like Syntax error: "(" unexpected. Run bash scripts with bash or with a #!/usr/bin/env bash shebang.
Do bash scripts need the .sh extension?
No. Linux decides how to run a file from its shebang line and its execute permission, not its name. The .sh extension is a convention that helps people and editors recognise the file.
How do I run a bash script on Windows?
Use WSL (Windows Subsystem for Linux) or Git Bash, then run bash script.sh as you would on Linux. Save the file with LF line endings; Windows-style CRLF endings cause errors such as /bin/bash^M: bad interpreter on Linux.
How do I debug a bash script?
Run it with bash -x script.sh, or add set -x near the top. Bash then prints each command, with variables already expanded, on standard error before running it, prefixed with +. Turn tracing off again with set +x.

Sources