How to write a basic bash script

Overview

A Bash script stores shell commands in a text file so the same task can run consistently. Begin with small, readable scripts and test them on non-critical data.

Create and run

Save this as hello.sh, make it executable, and run it from the current directory.

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

name=${1:-friend}
printf 'Hello, %s!\n' "$name"

chmod +x hello.sh
./hello.sh Ada

Important parts

  • The shebang chooses Bash through the environment
  • $1 is the first positional argument
  • ${1:-friend} supplies a default
  • set -euo pipefail catches many common errors but needs understanding
  • Comments begin with #
  • bash -n script.sh checks syntax without running commands

Safety and debugging

Quote variables, check paths, and avoid unnecessary sudo. Never test a script containing rm -rf against important directories.

Use bash -x script.sh to trace commands, but remember traces may reveal secrets.