Basic shell script for DevOps

Basic shell script for DevOps

  1. What is Shell Scripting?

Shell scripting is the art of writing scripts that are interpreted by the shell. A script is a series of commands saved in a file. Instead of entering commands manually, you can run a script to execute a sequence of commands automatically.

  1. Why Use Shell Scripts?

  • Automation: Automate repetitive tasks to save time.

  • Simplification: A single script can replace a complex series of commands.

  • Scheduled Tasks: Scripts can be scheduled to run at specific times or intervals using tools like cron.

  • Consistency: Ensures that tasks are always executed in the same way, reducing human error.

  1. Types of Shells

There are multiple types of shells available. Each has its own features, but bash (Bourne Again Shell) is the most commonly used and comes as the default on many Linux distributions. Others include sh (Bourne Shell), csh (C Shell), ksh (Korn Shell), and zsh (Z Shell).

  1. Shebang (#!)

The shebang #! at the beginning of a script indicates the interpreter that should be used to execute the script. For bash scripts, this typically looks like #!/bin/bash.

  1. Script Execution

Scripts can be executed in a couple of ways:

  • Direct Invocation: By marking the script as executable with chmod +x scriptname.sh and then running it directly: ./scriptname.sh.

  • Using a Shell: By invoking a shell to interpret the script: bash scriptname.sh.

  1. Variables and Parameters

Scripts often use variables to store and manipulate data. Parameters can be passed to scripts to make them more dynamic and versatile.

  1. Control Structures

To make decisions and control the flow of execution, scripts employ structures like if-else, loops (for, while), and case statements.

  1. Functions

Shell scripts can define and use functions, allowing for modular and more readable code.

  1. Comments and Best Practices

Comments (lines beginning with #, excluding the shebang) are essential for explaining the purpose and functionality of parts of a script. Following best practices, like proper indentation, meaningful variable names, and including comments, makes scripts maintainable and readable.

  1. Example

    If Statement:

    #!/bin/bash
    word="$1"
    if [ "$word" = 'hello' ]; then
    echo "Hii"
    else
    echo "bye"
    fi