Day 4: 90DaysOfChallenge

Day 4: 90DaysOfChallenge

Basic Linux Shell Scripting for DevOps Engineers

Shell scripting for DevOps refers to the practice of writing scripts using shell programming languages (such as Bash, PowerShell, or Python) to automate and streamline various tasks in the DevOps workflow. Shell scripts play a crucial role in the DevOps world as they enable automation, consistency, and efficiency in tasks such as deployment, configuration management, provisioning, monitoring, and more. The most common shell is called the "Bash" shell which comes by default with the computer. Bash stands for "Bourne Again Shell".

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

The #!/bin/bash is called a "shebang" (also known as a hashbang), and it is a special directive used at the beginning of a script to specify that Bash shell should be used to execute the script. Bash is a popular shell, and it provides powerful features and capabilities for scripting.

We can use #!/bin/sh instead of #!/bin/bash because the script does not rely on any Bash-specific features.

Write a Shell Script which prints "Hello World".

Firstly, we will create a bash file using nano which is a text editor and store the file name with .sh extension. We give nano first_script.sh and hit enter. This takes us to the nano editor where we give #!/bin/bash to specify that bash will be used for scripting. Then we use echo command to display the content echo "Hello World". Then, we save and exit from the editor. We then use bash first_script.sh to check the content of the file first_script.sh.

Output:

Write a Shell Script to take user input and print the variables.

To take user input - read command is used to take input from the user and store it in a variable. The variable is called by using a dollar sign followed by opening curly braces, variable name and then closing burly braces. Ex- ${variableName}.

In the below example, name is the variable preceded by the read command to take input from the user. The variable is then called in the last line by echo "Hello ${name}" command.

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

Below is the example where read -p is used to output the prompt string before reading user input and then the variables are declared num1 and num2. They are used in the if condition using ${num1} and ${num2} where -gt is used to compare the greater number in between the first and second number. ./ Operator followed by the shell filename is used to execute the shell script.

Output:

Write an script to demonstrate for loop with a example to print file list from a directory.

Below is the code to print directory list using for loop.

Output:

Thanks for reading my article.