Shell Scripting For DevOps

Shell Scripting For DevOps

What is Shell?

The shell is the command line interpreter. It translates commands entered by the user and converts them into a language that is understood by the kernel.

What is Shell Script?

The basic concept of Shell Script is a list of commands which are listed in the order of execution.

The shell script is used to automate the task in DevOps.

Shell scripting is an important tool for DevOps because it allows engineers to automate tasks like deploying applications, managing infrastructure and taking backups and because of this it can save time and reduce errors.

What is #!/bin/bash? can we write #!/bin/sh as well?

#!/bin/bash is called a shebang. It is the syntax that tells the shell which interpreter to use to run the scripts and as per syntax it will use the bash interpreter. Bash is a very popular shell and many Linux distributions use it as a default shell.

#!/bin/sh is also a shebang, and it tells the shell to use the Bourne shell interpreter.

So, you can use either #!/bin/bash or #!/bin/sh depending on your needs and the specific shell features you require for your script.

Examples of Shell Scripts

  • Write a Shell Script which prints "I will complete #90DaysOofDevOps challenge".
  1. Create a shell script: vim demo.sh

  2. write the commands:

    #!/bin/bash

    echo "I will complete #90DaysOofDevOps challenge"

  3. Give demo.sh file a execute permission: chmod 770 demo.sh

  4. Finally, run the script: bash demo.sh or ./demo.sh

  1. Write a Shell Script to take user input, input from arguments and print the variables.

  2. Write an Example of If else in Shell Scripting by comparing 2 numbers

  3. Write a script to create multiple directories using user inputs as an argument using for loop.

    #!/bin/bash

    echo "Directory Created"

    for ((i=$2; i<=$3; i++))

    do

    mkdir $1$i

    done

  4. We can use simple one-line commands to create multiple directories

    as Movie20 Movie21 Movie23 ...Movie50 .

    mkdir Movies{20..50}.sh

  5. Create a Script to backup all your work done till now.

    #!/bin/bash

    src=/home/ubuntu/learndevops

    trg=/home/ubuntu/backup

    filename=$(date "+%Y-%m-%d-%H-%M-%S")

    tar -czvf $trg/$filename.tar.gz $src

    echo "Backup complete"

  6. We can also automate the backup script like every minute, week, and month using cron and crontab.

    Cron is the system's main scheduler for running jobs or tasks.

    Crontab allows the user to edit, add or delete entries to cron and it contains all scheduler information.

    In this example, we are taking backup every 2 minutes.

    First, write crontab -e to edit and add the below command.

    \/2 \ * * * bash /home/ubuntu/backup/backup.sh

    In this blog, we have learned about what is a shell script with some examples which will help us to automate manual tasks.

    Thank you for reading the blog.

    Suggestions are always welcome. Thank you !!