Skip to content

Latest commit

 

History

History
237 lines (189 loc) · 5.71 KB

4. Scripting Basics.md

File metadata and controls

237 lines (189 loc) · 5.71 KB

Scripting Basics

Shell scripting is a powerful way to automate tasks, manage system operations, and streamline workflows on a Linux system. This guide covers the foundational concepts and practices of creating and using shell scripts.

1. Introduction to Shell Scripting

  • What is Shell Scripting?

    • Shell scripting involves writing a sequence of commands in a file (a script) that the shell can execute to perform tasks automatically.
    • Commonly used for system administration, task automation, and simplifying repetitive tasks.
  • Why Use Shell Scripts?

    • Efficiency: Automates repetitive tasks, reducing manual effort.
    • Consistency: Ensures tasks are performed the same way every time.
    • Flexibility: Can be used for a wide range of tasks, from simple file operations to complex system administration tasks.

2. Shell Scripting Basics

2.1 Writing Your First Shell Script

  • Creating a Script File:

    • Create a new file with a .sh extension (e.g., myscript.sh).
    • Start the script with the shebang #! followed by the path to the shell.
      #!/bin/bash
    • Add your commands below the shebang.
  • Basic Example:

    #!/bin/bash
    echo "Hello, World!"
    • Explanation:
      • #!/bin/bash: Specifies the script should be run using the Bash shell.
      • echo "Hello, World!": Prints "Hello, World!" to the terminal.

2.2 Making the Script Executable

  • Setting Execute Permissions:
    • Use the chmod command to make the script executable:
      chmod +x myscript.sh
    • Run the script:
      ./myscript.sh

2.3 Variables in Shell Scripts

  • Defining Variables:

    • Assign values to variables using the = operator:
      NAME="John"
    • Access the variable by prefixing it with $:
      echo "Hello, $NAME!"
  • Example:

    #!/bin/bash
    NAME="Linux User"
    echo "Welcome, $NAME!"

2.4 Basic Input and Output

  • Reading User Input:

    • Use the read command to get input from the user:
      echo "Enter your name:"
      read USERNAME
      echo "Hello, $USERNAME!"
  • Redirecting Output:

    • Redirect command output to a file using >:
      echo "This is a log entry." > logfile.txt
  • Appending to a File:

    • Append output to a file using >>:
      echo "This is another log entry." >> logfile.txt

3. Control Structures

3.1 Conditional Statements

  • if Statement:

    • Used to execute code based on a condition:
      if [ "$USERNAME" == "admin" ]; then
        echo "Welcome, Administrator!"
      else
        echo "Access Denied."
      fi
  • Comparison Operators:

    • Numeric comparisons: -eq, -ne, -lt, -le, -gt, -ge.
    • String comparisons: ==, !=.

3.2 Loops

  • for Loop:

    • Used to iterate over a list of items:
      for FILE in /path/to/directory/*; do
        echo "Processing $FILE"
      done
  • while Loop:

    • Repeats a block of code while a condition is true:
      COUNTER=1
      while [ $COUNTER -le 5 ]; do
        echo "Counter: $COUNTER"
        ((COUNTER++))
      done

3.3 Case Statements

  • case Statement:
    • Used to execute different code blocks based on the value of a variable:
      case $1 in
        start)
          echo "Starting service..."
          ;;
        stop)
          echo "Stopping service..."
          ;;
        restart)
          echo "Restarting service..."
          ;;
        *)
          echo "Usage: $0 {start|stop|restart}"
          ;;
      esac

4. Functions in Shell Scripts

4.1 Defining Functions

  • Basic Function Definition:

    • Define a function using the following syntax:
      my_function() {
        echo "This is a function"
      }
  • Calling a Function:

    • Call the function by its name:
      my_function

4.2 Passing Arguments to Functions

  • Accessing Function Arguments:
    • Function arguments are accessed using $1, $2, etc.:
      greet() {
        echo "Hello, $1!"
      }
      greet "John"

4.3 Returning Values from Functions

  • Using return:
    • Use the return command to exit a function with a status:
      add() {
        return $(($1 + $2))
      }
      add 3 5
      echo "Sum: $?"
    • Note that return is used for numeric status codes; to return strings or other values, use echo.

5. Scripting Best Practices

5.1 Code Readability

  • Use Comments:

    • Add comments to explain the purpose of code blocks:
      # This script greets the user
      echo "Hello, $USER!"
  • Consistent Naming:

    • Use meaningful and consistent variable and function names.

5.2 Error Handling

  • Check Command Execution:

    • Use set -e to exit the script if any command fails:
      set -e
    • Alternatively, check the exit status of commands using $?.
  • Use trap for Cleanup:

    • Ensure resources are cleaned up in case of errors:
      trap "echo 'Cleaning up...'; exit" INT TERM

5.3 Testing and Debugging

  • Use set -x for Debugging:

    • Enable script debugging to see each command before it's executed:
      set -x
  • Test Incrementally:

    • Test scripts incrementally by adding and testing small sections of code.

Conclusion

Shell scripting is a fundamental skill for Linux users and administrators, enabling automation and efficient system management. By mastering the basics of shell scripting, you can create powerful scripts to streamline tasks, manage systems, and improve productivity.


Previous: Backup and Recovery