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
Type this:
#!/bin/bash
echo "Hello, World!"
echo "Today is $(date)"
echo "You are: $(whoami)"
Save and exit (Ctrl+O, Ctrl+X).
The Shebang Line
#!/bin/bash
This must be the first line. It tells the system which interpreter to use.
| Shebang | Interpreter |
|---|---|
#!/bin/bash | Bash shell |
#!/bin/sh | POSIX shell |
#!/usr/bin/env python3 | Python 3 |
#!/usr/bin/env node | Node.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:
Run Your Script
The ./ means "current directory". Without it, bash looks in PATH and won't find your script.
Alternative: Run with bash
This explicitly uses bash, ignoring the shebang. Works but less portable.
Comments
Document your code:
#!/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
#!/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"
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
Why do you need to use './' before your script name?
Quick Reference
| Step | Command |
|---|---|
| Create script | nano script.sh |
| Add shebang | #!/bin/bash (first line) |
| Make executable | chmod +x script.sh |
| Run script | ./script.sh |
Key Takeaways
- Scripts are text files with commands
- Start with
#!/bin/bash(the shebang) chmod +xmakes 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.