Your First Script

You've been typing commands one at a time. Now let's chain them into scripts that run automatically.

What Is a Shell Script?

A text file containing commands. Instead of typing 10 commands, you run one script.

Create Your First Script

Terminal
$nano hello.sh

Type this:

hljs bash
#!/bin/bash
echo "Hello, World!"
echo "Today is $(date)"
echo "You are: $(whoami)"

Save and exit (Ctrl+O, Ctrl+X).

The Shebang Line

hljs bash
#!/bin/bash

This must be the first line. It tells the system which interpreter to use.

ShebangInterpreter
#!/bin/bashBash shell
#!/bin/shPOSIX shell
#!/usr/bin/env python3Python 3
#!/usr/bin/env nodeNode.js

No Spaces!

The shebang must be exactly #!/bin/bash - no spaces before # and no blank lines above it.

Make It Executable

Scripts need execute permission:

Terminal
$ls -l hello.sh
-rw-r--r-- 1 user user 85 Jan 14 10:30 hello.sh
$chmod +x hello.sh
$ls -l hello.sh
-rwxr-xr-x 1 user user 85 Jan 14 10:30 hello.sh

Run Your Script

Terminal
$./hello.sh
Hello, World! Today is Tue Jan 14 10:30:45 UTC 2025 You are: user

The ./ means "current directory". Without it, bash looks in PATH and won't find your script.

Alternative: Run with bash

Terminal
$bash hello.sh
(works without chmod +x)

This explicitly uses bash, ignoring the shebang. Works but less portable.

Comments

Document your code:

hljs bash
#!/bin/bash
# This script greets the user
# Author: Your Name
# Date: 2025-01-14

echo "Hello!"  # inline comment

Everything after # is ignored (except the shebang).

A More Useful Script

Terminal
$nano backup.sh
hljs bash
#!/bin/bash
# Simple backup script

SOURCE="/home/user/documents"
DEST="/home/user/backup"
DATE=$(date +%Y-%m-%d)

echo "Starting backup..."
cp -r "$SOURCE" "$DEST/documents-$DATE"
echo "Backup complete: $DEST/documents-$DATE"
Terminal
$chmod +x backup.sh
$./backup.sh
Starting backup... Backup complete: /home/user/backup/documents-2025-01-14

Script Location

Put frequently used scripts in ~/bin or /usr/local/bin. Add to PATH for easy access.

Common First Mistakes

Forgetting chmod +x

bash: ./script.sh: Permission denied

Fix: chmod +x script.sh

Wrong Path

bash: script.sh: command not found

Fix: Use ./script.sh not script.sh

Windows Line Endings

bash: ./script.sh: /bin/bash^M: bad interpreter

Fix: sed -i 's/\r$//' script.sh or use Linux editor

Knowledge Check

Why do you need to use './' before your script name?

Quick Reference

StepCommand
Create scriptnano script.sh
Add shebang#!/bin/bash (first line)
Make executablechmod +x script.sh
Run script./script.sh

Key Takeaways

  • Scripts are text files with commands
  • Start with #!/bin/bash (the shebang)
  • chmod +x makes scripts executable
  • Run with ./script.sh
  • Use comments to document your code
  • Scripts save time on repetitive tasks

Next: using variables to make scripts dynamic.