DevOps- Get Started with Shell Scripting
In your day-to-day work as a DevOps engineer, you’ll come across various scenarios where we need to automate stuff to save us time and be more productive. Scripts will be used in the CI/CD workflow in one form or another. The following are some of the most commonly used scripting languages.
- Bash/Shell
- Golang
- Python
In this tutorial, we will learn about Shell scripting specifically.
Prerequisites
- Comfortable with Linux commands
Let’s get started
1. Initial Script
- Create a directory inside which we’ll create a script file
mkdir scripts
cd scripts
touch script.sh
What is #!/bin/bash?
This is known as She-bang. It’s the most popular shell used for user login on a Linux system is /bin/bash. This line is always written on top of shell script.
What is echo?
echo is the print statement for the bash. Whatever is written after echo will be printed when we run the script. Ex: echo "Hello world"```
Let’s Open the script.sh file & write the first script. This is what your 1st script will look like.
This will simply print the statement “My first shell script” when we run it. To run the script we run the following command:
bash script.sh
2. Variables
To use variables we simply use define the variable followed by the value
3. User Input
To get input from the user we use the “read” command.
On running, the user will need to enter the age. On entering, we get the output as specified in the echo statement.
4. Arguments
We can specify arguments when running a bash file.
bash script.sh args1
args1 is an argument that can be accessed inside the script using $1.
5. If-Else
It works the same way as in other languages. You specify the condition. If it satisfies it goes inside the initial block otherwise inside the else block. Here we are checking if the argument is “hello” and on that basis decide the output.
bash script.sh hello