Your First Shell Script

Let’s create your first shell script step by step. This hands-on approach will help you understand the basics and get you started with shell scripting.

Step 1: Create Your First Script

Using a Text Editor

Open your favorite text editor and create a new file called hello.sh:

# Using nano
$ nano hello.sh

# Using vim
$ vim hello.sh

# Using VS Code
$ code hello.sh

Write the Script

Type the following content into your file:

#!/bin/bash
# My first shell script
# Purpose: Display a greeting message

echo "Hello, World!"
echo "Welcome to shell scripting!"
echo "Today's date is: $(date)"
echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"

Save the File

  • nano: Press Ctrl+X, then Y, then Enter
  • vim: Press Esc, type :wq, then Enter
  • VS Code: Press Ctrl+S

Step 2: Understanding the Script

Let’s break down each part:

Shebang Line

#!/bin/bash
  • Purpose: Tells the system to use bash to execute this script
  • Must be: The very first line of the script
  • Alternative: #!/bin/sh for POSIX compatibility

Comments

# My first shell script
# Purpose: Display a greeting message
  • Purpose: Document what the script does
  • Syntax: Lines starting with # (except shebang)
  • Best Practice: Always comment your scripts

Commands

echo "Hello, World!"
  • echo: Command to display text
  • Quotes: Protect text with spaces and special characters

Command Substitution

echo "Today's date is: $(date)"
  • $(command): Executes command and substitutes its output
  • Alternative: Backticks `date` (older syntax)

Step 3: Make the Script Executable

Before you can run the script, you need to make it executable:

# Check current permissions
$ ls -l hello.sh
-rw-r--r-- 1 user user 245 Jan 15 10:30 hello.sh

# Make it executable
$ chmod +x hello.sh

# Verify permissions changed
$ ls -l hello.sh
-rwxr-xr-x 1 user user 245 Jan 15 10:30 hello.sh

Understanding Permissions

  • r: Read permission
  • w: Write permission
  • x: Execute permission
  • First rwx: Owner permissions
  • Second rwx: Group permissions
  • Third rwx: Other users permissions

Step 4: Run Your Script

There are several ways to execute your script:

Method 1: Direct Execution

$ ./hello.sh
Hello, World!
Welcome to shell scripting!
Today's date is: Mon Jan 15 10:35:22 EST 2024
Current user: john
Current directory: /home/john/scripts

Method 2: Using bash Command

$ bash hello.sh
# Same output as above

Method 3: Using sh Command

$ sh hello.sh
# Same output as above

Method 4: Full Path

$ /home/john/scripts/hello.sh
# Same output as above

Step 5: Enhance Your Script

Let’s make the script more interactive:

#!/bin/bash
# Enhanced greeting script
# Purpose: Interactive greeting with user input

echo "==================================="
echo "    Welcome to Shell Scripting!"
echo "==================================="
echo

# Get user's name
echo "What's your name?"
read name

# Get user's favorite color
echo "What's your favorite color?"
read color

# Display personalized greeting
echo
echo "Hello, $name!"
echo "I see your favorite color is $color."
echo "That's a great choice!"
echo
echo "System Information:"
echo "==================="
echo "Date: $(date)"
echo "User: $(whoami)"
echo "Home Directory: $HOME"
echo "Current Directory: $(pwd)"
echo "Shell: $SHELL"
echo
echo "Have a great day, $name!"

Save this as enhanced_hello.sh and run it:

$ chmod +x enhanced_hello.sh
$ ./enhanced_hello.sh

Step 6: Adding Error Handling

Let’s add some basic error handling:

#!/bin/bash
# Script with error handling
# Purpose: Demonstrate basic error handling

set -e  # Exit immediately if a command exits with a non-zero status

echo "Starting script..."

# Check if a directory exists
if [ -d "/home" ]; then
    echo "✓ /home directory exists"
else
    echo "✗ /home directory not found"
    exit 1
fi

# Try to create a test file
TEST_FILE="test_file.txt"
echo "Creating test file: $TEST_FILE"

if echo "This is a test" > "$TEST_FILE"; then
    echo "✓ Test file created successfully"

    # Clean up
    rm "$TEST_FILE"
    echo "✓ Test file cleaned up"
else
    echo "✗ Failed to create test file"
    exit 1
fi

echo "Script completed successfully!"

Step 7: Script with Functions

Let’s organize code using functions:

#!/bin/bash
# Script with functions
# Purpose: Demonstrate function usage

# Function to display a separator
show_separator() {
    echo "=================================="
}

# Function to display system info
show_system_info() {
    echo "System Information:"
    echo "OS: $(uname -s)"
    echo "Kernel: $(uname -r)"
    echo "Architecture: $(uname -m)"
    echo "Hostname: $(hostname)"
}

# Function to display disk usage
show_disk_usage() {
    echo "Disk Usage:"
    df -h | head -5
}

# Main script execution
main() {
    show_separator
    echo "    System Status Report"
    show_separator
    echo

    show_system_info
    echo

    show_disk_usage
    echo

    show_separator
    echo "Report generated on: $(date)"
    show_separator
}

# Call main function
main

Common Beginner Mistakes

1. Forgetting the Shebang

# Wrong - no shebang
echo "Hello World"

# Correct
#!/bin/bash
echo "Hello World"

2. Not Making Script Executable

# This will fail
$ ./myscript.sh
bash: ./myscript.sh: Permission denied

# Fix it
$ chmod +x myscript.sh
$ ./myscript.sh

3. Wrong Path in Shebang

# Might not work on all systems
#!/usr/bin/bash

# More portable
#!/bin/bash

# Most portable
#!/usr/bin/env bash

4. Spaces in Variable Assignment

# Wrong - spaces around =
name = "John"

# Correct - no spaces
name="John"

Best Practices for Beginners

1. Always Use Shebang

#!/bin/bash

2. Add Comments

# What the script does
# Author and date
# Usage instructions

3. Use Meaningful Names

# Good
backup_directory="/backup"
user_name="john"

# Avoid
dir="/backup"
n="john"

4. Quote Variables

# Good
echo "Hello, $name"
cp "$source_file" "$destination"

# Risky
echo Hello, $name
cp $source_file $destination

5. Check for Errors

#!/bin/bash
set -e  # Exit on error

# Or check individual commands
if ! command_that_might_fail; then
    echo "Command failed!"
    exit 1
fi

Testing Your Scripts

1. Syntax Check

$ bash -n myscript.sh
# No output means no syntax errors

2. Debug Mode

$ bash -x myscript.sh
# Shows each command as it's executed

3. Use shellcheck

$ shellcheck myscript.sh
# Provides suggestions for improvement

Next Steps

Now that you’ve created your first script, you can:

  1. Experiment: Modify the examples and see what happens
  2. Practice: Create scripts for tasks you do regularly
  3. Learn More: Study variables, conditionals, and loops
  4. Read Others’ Scripts: Look at system scripts in /etc/init.d/
  5. Use Version Control: Start tracking your scripts with git

Congratulations! You’ve written and executed your first shell script. This is the foundation for all the advanced scripting techniques you’ll learn in the following chapters.