DevOps 107: Getting Started with Bash Scripting - A Beginner's Guide

ยท

6 min read

DevOps 107:  Getting Started with Bash Scripting - A Beginner's Guide

Shell scripting, is a powerful tool for automating repetitive tasks, managing system configurations, and performing various system administration tasks. Bash is the most popular shell scripting language used on Linux and Unix systems. This blog will discuss the basics of shell scripting and explore some common use cases.

What is Bash?

Bash is a Unix shell, a command-line interface for interacting with the operating system. Bash provides a scripting language that allows users to write scripts to automate tasks and customize their system environments. Bash scripts are typically run from the command line, but can be executed by other programs or scheduled to run automatically.

Bash stands for - Bourne Again Shell

Basic Structure of a Bash Script

A Bash script is a plain text file that contains a series of commands to be executed by the shell. Here is the basic structure of a Bash script:

#!/bin/bash

# Comments can be added here
# Define variables and functions
variable=value

function_name() {
  # Function code here
}

# Main program code
command1
command2

In the first line of the script, #!/bin/bash, is called the shebang line. It tells the system to use the Bash shell to execute the script. Comments can be added to the script using the '#' character. Variables and functions can be defined at the top of the script, followed by the main program code.

Variables and Data Types

Variables in Bash are defined using the '=' operator. Here's an example:

greeting="Hello, world!"

Bash is a dynamically-typed language, which means that variables do not have a fixed data type. Bash can handle strings, integers, and floating-point numbers, as well as arrays and other data structures.

Here's an example of how to use a variable in a script:

#!/bin/bash

greeting="Hello, world!"
echo $greeting

In this example, the variable greeting is defined as "Hello, world!", and the echo command is used to print the value of the variable to the console.

Conditional Statements

Bash supports a variety of conditional statements, including if, else, and elif. Here's an example:

#!/bin/bash

# Read input
read -p "Enter the number: " number

if [ $number -gt 100 ]
then 
    echo "Value is greater than 100"
elif [ $number -lt 100 ]
then
    echo "Value is less than 100"
else
    echo "Value is equal to 100"
fi

In this example, the script prompts the user to enter a number and then performs a conditional check on the number variable. If the number is greater than 100, the script outputs "Value is greater than 100" to the console. If the number is less than 100, the script outputs "Value is less than 100" to the console. If the number is exactly equal to 100, the script outputs "Value is equal to 100" to the console.

Nested If Else

#!/bin/bash

#nested if statement

if [ $1 -gt 50 ]
then
    echo "Number is greater than 50"
    if (( $1 % 2 == 0))
    then
        echo "And it is an even number"
    else 
        echo "And it is an odd number"
    fi
fi

The script takes an input number as a command-line argument and checks if it is greater than 50. If it is, the script outputs "Number is greater than 50". Then if the number is even, the script outputs "And it is an even number" else the script outputs "And it is an odd number" to the console.

Loops

Bash also supports several types of loops, including for, while and until. Here's an example:

  1. For Loop

     #!/bin/bash
    
     for i in {1..10}
     do
       echo $i
     done
    

    In this example, the script uses a for loop to iterate over the values 1 through 10 and outputs each value to the console.

  2. While Loop

     #!/bin/bash
    
     read -p "Enter starting number: " snum
     read -p "Enter ending number: " enum
     while [[ $snum -le $enum ]];
     do
         echo $snum
         ((sum++))
     done
     echo "This is what we wanted to print again"
    

    This script is a basic Bash script that prompts the user for a starting and ending number and then outputs all of the numbers between them, one at a time. It also increments a counter called sum for each number in the range.

  3. Until Loop

     #!/bin/bash
    
     i=1
     until [ $i -gt 10 ]
         do
         echo $i
         ((i++))
     done
    

    This script uses a until loop to output the numbers from 1 to 10 to the console.

Functions

Bash supports the use of functions, which can be used to group related commands together and reuse code. Here's an example:

#!/bin/bash

function greet {
  echo "Hello, $1!"
}

greet "world"

In this example, the script defines a function called, greet which takes a parameter and outputs "Hello, {parameter}!". The function is then called with the parameter "world".

Arrays

Bash supports arrays, which can be used to store multiple values in a single variable. Here's an example:

#!/bin/bash

my_array=(foo bar baz)

echo ${my_array[1]}

In this example, the script defines an array called my_array with three elements, and then outputs the second element ("bar") to the console using the array syntax.

Command Substitution

Bash supports command substitution, which allows the output of a command to be used as input to another command. Here's an example:

#!/bin/bash

current_dir=$(pwd)
echo "The current directory is $current_dir"

In this example, the $(pwd) command is used to get the current directory, and the output is saved to the current_dir variable. The variable is then used in the echo command to output the current directory to the console.

File Operations

Bash can also be used to perform various file operations, such as creating, copying, and deleting files. Here are a few examples:

#!/bin/bash

# Create a new file
touch my_file.txt

# Copy a file
cp my_file.txt my_file_copy.txt

# Delete a file
rm my_file.txt

In this example, the script creates a new file called my_file.txt, copies it to a new file called my_file_copy.txt, and then deletes the original file.

Conclusion

Bash scripting offers a wide range of features and functionality for automating tasks and managing system configurations. In this blog, we covered the basics of Bash scripting including variables, data types, conditional statements, and loops, as well as the advanced features discussed above, you should be well on your way to writing powerful and efficient Bash scripts. Remember to test your scripts thoroughly and always use caution when performing system operations. With a little practice, you can write Bash scripts to automate repetitive tasks and save time and effort in your system administration work.

Stay tuned for more such blogs and subscribe to my newsletter to not miss any of my blogs.

Thank you for reading! I hope you enjoyed this blog post and found it informative and valuable. If you have any questions or comments, please don't hesitate to leave them below. I'm always happy to engage with my readers and discuss various topics.

Follow my DevOps Series ๐Ÿš€

Reach Out To Me On Linkedin: Raj Panchal

Website: rajpanchal.in

Did you find this article valuable?

Support Raj Panchal by becoming a sponsor. Any amount is appreciated!

ย