Your First Script

A shell script is a text file of commands; the shebang line says which interpreter runs it.

Syntax#!/bin/bash # commands go here

A shell script is just a file containing commands you could type by hand, saved so you can run them all at once.

The shebang

The first line must be a shebang: #! followed by the path to the interpreter. For bash that is:

#!/bin/bash

This tells Linux to run the file with bash.

Making it run

A new script is not executable yet. Give it the execute bit, then run it with ./:

  1. Write the file, starting with the shebang.
  2. chmod +x script.sh — make it executable.
  3. ./script.sh — run it.

Example

Example · bash
#!/bin/bash
# hello.sh - my first script
echo "Hello from a script!"
echo "Today is $(date)"

# Then, in the terminal:
#   chmod +x hello.sh
#   ./hello.sh

When to use it

  • A sysadmin adds '#!/bin/bash' as the first line of a maintenance script so it always runs with Bash regardless of the user's login shell.
  • A developer uses '#!/usr/bin/env python3' so a Python script finds the correct interpreter on any system where Python 3 is installed.
  • A DevOps engineer uses '#!/usr/bin/env node' at the top of a Node.js CLI tool so it can be executed directly as './tool.js'.

More examples

Hello World Bash script

Shows a minimal script with a shebang, a comment, and command substitution, plus how to make it executable.

Example · bash
#!/bin/bash
# My first script
echo "Hello, $(whoami)! Today is $(date +%A)."

# Make it executable and run
chmod +x hello.sh
./hello.sh
# Hello, alice! Today is Wednesday.

Portable Python shebang

Uses /usr/bin/env so the script works on any system where python3 is on PATH, not just /usr/bin/.

Example · bash
#!/usr/bin/env python3
# env finds python3 on PATH regardless of install location
import sys
print(f'Python {sys.version} on {sys.platform}')

Shell script with strict mode

Adds 'set -euo pipefail' immediately after the shebang to make the script fail fast on any error.

Example · bash
#!/bin/bash
set -euo pipefail
# -e   exit on any error
# -u   treat unset variables as errors
# -o pipefail  catch errors in pipelines

BACKUP_DIR="/var/backups/db"
mkdir -p "$BACKUP_DIR"
echo "Backup directory ready: $BACKUP_DIR"

Discussion

  • Be the first to comment on this lesson.