Creating Your First Script
Shell scripts are text files containing commands that run automatically. They're essential for automation and repetitive tasks.
What is a Shell Script?
A shell script is:
- A text file with shell commands
- Executable like a program
- Interpreted line by line
- Used for automation
Your First Script
Create a file called hello.sh:
#!/bin/bash
echo "Hello, World!"
The Shebang Line
The first line #!/bin/bash is the shebang (or hashbang):
#!/bin/bash # Use bash
#!/bin/sh # Use sh (more portable)
#!/usr/bin/env bash # Find bash in PATH
#!/usr/bin/python3 # Python script
It tells the system which interpreter to use.
Creating a Script
Step 1: Create the File
touch myscript.sh
Step 2: Add Content
cat > myscript.sh << 'EOF'
#!/bin/bash
echo "Script started"
date
echo "Script finished"
EOF
Step 3: Make Executable
chmod +x myscript.sh
Step 4: Run It
./myscript.sh
Exercise: View a Script
Look at an existing script to understand its structure:
Running Scripts
Multiple ways to run:
./script.sh # If executable
bash script.sh # Explicit interpreter
source script.sh # In current shell
. script.sh # Same as source
Script Structure
A typical script:
#!/bin/bash
# Description: What this script does
# Author: Your name
# Date: 2024-01-01
# Configuration
NAME="World"
# Main logic
echo "Hello, $NAME!"
# Exit with status
exit 0
Comments
# This is a single line comment
: '
This is a
multi-line comment
'
Exit Codes
Scripts return exit codes:
exit 0 # Success
exit 1 # General error
exit 2 # Misuse of command
Check last exit code:
echo $? # 0 = success, non-zero = error
Script Example
#!/bin/bash
# Simple backup script
SOURCE="/home/user/documents"
DEST="/backup"
DATE=$(date +%Y%m%d)
echo "Starting backup..."
cp -r "$SOURCE" "$DEST/backup_$DATE"
echo "Backup complete!"
Debugging Scripts
bash -x script.sh # Print each command
bash -n script.sh # Check syntax only
set -x # Enable debug in script
set +x # Disable debug
Best Practices
- Always include shebang:
#!/bin/bash - Add comments: Explain what the script does
- Use meaningful names:
backup_database.shnotscript1.sh - Handle errors: Check command success
- Quote variables:
"$VAR"not$VAR - Test before deploying: Use a safe environment
Key Takeaways
- Scripts start with shebang (
#!/bin/bash) - Make executable with
chmod +x - Run with
./script.shorbash script.sh - Use comments to document code
- Exit codes indicate success (0) or failure (non-zero)

