Shell Scripting in Linux

Shell scripting in Linux allows you to automate tasks, manage system processes, and handle repetitive tasks efficiently. In this tutorial, we’ll explore the basics of shell scripting and create a simple script to get started.

Step 1: What Is a Shell Script?

A shell script is a file containing a series of commands that the shell (like Bash) executes. Shell scripts are used for automation, file processing, and task scheduling.

Step 2: Creating Your First Shell Script

Follow these steps to create and execute your first shell script:

  1. Open a terminal.
  2. Create a new file with the touch command:
    touch myscript.sh
  3. Edit the file using a text editor like nano or vim:
    nano myscript.sh
  4. Add the following lines to the file:
    #!/bin/bash
        echo "Hello, World!"
        echo "Today is: $(date)"
  5. Save and close the editor (Ctrl+O, Enter, Ctrl+X in nano).
  6. Make the script executable:
    chmod +x myscript.sh
  7. Run the script:
    ./myscript.sh

Step 3: Understanding the Script

  • #!/bin/bash: Specifies the script should run in the Bash shell.
  • echo: Prints text to the terminal.
  • $(date): Executes the date command and substitutes its output.

Step 4: Adding Variables

Variables store data for use in scripts:

#!/bin/bash
    name="Alice"
    echo "Hello, $name!"

Step 5: Using Conditional Statements

Include if statements for decision-making:

#!/bin/bash
    read -p "Enter a number: " number
    if [ $number -gt 10 ]; then
        echo "The number is greater than 10."
    else
        echo "The number is 10 or less."
    fi

Step 6: Adding Loops

Use loops to perform repetitive tasks:

#!/bin/bash
    for i in {1..5}; do
        echo "Iteration $i"
    done

Step 7: Handling Command-Line Arguments

Access arguments passed to the script:

#!/bin/bash
    echo "Script name: $0"
    echo "First argument: $1"
    echo "Second argument: $2"

Step 8: Scheduling Scripts with Cron

Automate script execution using cron jobs:

  1. Edit the crontab:
    crontab -e
  2. Add a cron job to run the script daily at 8 AM:
    0 8 * * * /path/to/myscript.sh

Next Steps

Explore advanced topics like functions, error handling, and interacting with files and processes. Shell scripting is a powerful skill for automating workflows and managing Linux systems effectively. Happy scripting!