DEV Community

Cover image for Supercharge Your Automation: Mastering Shell Scripting
Lionel♾️☁️ for AWS Community Builders

Posted on • Edited on • Originally published at softwaresennin.dev

Supercharge Your Automation: Mastering Shell Scripting

Bash (Bourne Again Shell) is one of, if not the most powerful scripting languages that can be used to automate chores and conduct numerous operations in the Linux terminal. Here are some basic commands and ideas to get you started with Bash programming.

Writing a script

To start, give your script any name of your choice. We will call it my_script. However, it must conclude with .sh. Reason being that it is an internationally accepted convention of naming for bash scripts. To begin your shell script journey, open the file in your favourite text editor (vi, vim, nano, gedit) and type the first line.

my_script.sh

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode

The #! /bin/bash line is known as the shebang or hashbang, because it specifies the interpreter that will be used to execute the script. #!/bin/bash indicates that the script should be interpreted and executed using the Bash shell in this case.

Script execution:

Navigate to the location where you saved the script file in your terminal. Before executing a script, we need to make sure that it has the appropriate permissions that it needs. For that, we will run the chmod command to add the execute permission to our script.

chmod +x myscript.sh
Enter fullscreen mode Exit fullscreen mode

Now it has the execute x permission, the next step is to use the following command to run the script:

./my_script.sh
Enter fullscreen mode Exit fullscreen mode

You won't see any output at this point because we haven't written anything other than the shebang line. Let's throw in some fun stuff.

Display instructions:

To print statements or messages in the terminal, use the echo command. As an example:

echo Hello, World!
Enter fullscreen mode Exit fullscreen mode

Hello World will appear in your terminal.

Variables:

The assignment operator (=) is used in Bash to assign values to variables. Variable names are typically uppercase and can include letters, digits, and underscores. Here's an illustration:

NAME="Lionel" 
echo "My name is $NAME"
Enter fullscreen mode Exit fullscreen mode

The output will be as follows.

My name is Lionel
Enter fullscreen mode Exit fullscreen mode

User Input

In Bash, you can use the read command to read user input. Basically, it will prompt you for a value and save it in a variable. As an example:

read -p "Enter your name: " TYPE_YOUR_NAME_HERE
echo "Hello $NAME, nice to meet you!"
Enter fullscreen mode Exit fullscreen mode

The following is the output.

Enter your name: Lionel
Hello Lionel, nice to meet you!
Enter fullscreen mode Exit fullscreen mode

Conditional Expressions:

To regulate the flow of your script, Bash supports a variety of conditional statements. Here are a couple such examples:

If Statement in Simple Form:

if [ "$NAME" == "Lionel" ]
then
  echo "Your name is Lionel"
fi
Enter fullscreen mode Exit fullscreen mode

If Statement followed by Else:

if [ "$NAME" == "Lionel" ]
then
  echo "Your name is Lionel"
else
  echo "Your name is not Lionel"
fi
Enter fullscreen mode Exit fullscreen mode

Else, If statement

if [ "$NAME" == "Lionel" ]
then
  echo "Your name is Lionel"
elif [ "$NAME" == "Jack" ]
then
  echo "Your name is Jack"
else
  echo "Your name is NOT Lionel or Jack"
fi
Enter fullscreen mode Exit fullscreen mode

There are many ways of comparing two numbers in shell scripting. An example is the -gt (Greater Than) operator. As seen below:

NUM1=3 
NUM2=5

if [ "$NUM1" -gt "$NUM2" ] 
then 
    echo "$NUM1 is greater than $NUM2"
else 
    echo "$NUM1 is less than $NUM2"
fi
Enter fullscreen mode Exit fullscreen mode

Since 5 which is in the variable, NUM2 is always greater than 3 which is in variable, NUM1. So the output of this will be as follows

3 is less than 5
Enter fullscreen mode Exit fullscreen mode

There are many other operators that can be used for comparism. Some examples include:

  • Equal to: == or =

    • Example: [ "$var1" == "$var2" ]
    • Checks if $var1 is equal to $var2.
  • Not equal to: !=

    • Example: [ "$var1" != "$var2" ]
    • Checks if $var1 is not equal to $var2.
  • Greater than: >

    • Example: [ "$var1" -gt "$var2" ]
    • Checks if $var1 is greater than $var2.
  • Greater than or equal to: -ge

    • Example: [ "$var1" -ge "$var2" ]
    • Checks if $var1 is greater than or equal to $var2.
  • Less than: <

    • Example: [ "$var1" -lt "$var2" ]
    • Checks if $var1 is less than $var2.
  • Less than or equal to: -le

    • Example: [ "$var1" -le "$var2" ]
    • Checks if $var1 is less than or equal to $var2.

The following is an example of a script that checks whether a file with the given name exists or not.

FILE="test.txt"
if [ -e "$FILE" ]
then
  echo "$FILE exists"
else
  echo "$FILE does not exist"
fi
Enter fullscreen mode Exit fullscreen mode

Case Statement:

The case statement enables you to compare the value of a variable to numerous patterns and run distinct blocks of code based on the pattern that matches.

The following is an example of code.

read -p "Are you 21 or over? Y/N " ANSWER

case "$ANSWER" in
    [yY] | [yY][eE][sS])
        echo "You can have a beer :)"
        ;;
    [nN] | [nN][oO])
        echo "Sorry, no drinking"
        ;;
    *)
        echo "Please enter y/yes or n/no"
        ;;
esac
Enter fullscreen mode Exit fullscreen mode

The output of the preceding code is as follows:

# Example 1
Are you 21 or over? Y/N y
You can have a beer :)
# Example 2
Are you 21 or over? Y/N N
Sorry, no drinking
Enter fullscreen mode Exit fullscreen mode

Simple For loop

The for loop lets you traverse or iterate over a list of values, performing a set of actions for each one.

NAMES="Brad Kevin Alice Mark"
for NAME in $NAMES
do
    echo "Hello $NAME"
done
Enter fullscreen mode Exit fullscreen mode

The output will be as follows:

Hello Brad
Hello Kevin
Hello Alice
Hello MarkWhile loop
Enter fullscreen mode Exit fullscreen mode

In shell scripting, the while loop allows you to execute a block of code continuously as long as a given condition is true. Here's an illustration of a for loop.

LINE=1
while read -r CURRENT_LINE
do
    echo "$LINE: $CURRENT_LINE"
    ((LINE++))
done < "./contents.txt"
Enter fullscreen mode Exit fullscreen mode

Functions:

You can define and use functions in shell scripting to encapsulate a block of code that can be executed several times throughout your script. For example, let us create a function called sayHello(). After creating that function, type the command sayHello() to call the function.

sayHello() {
    echo "Hello World"
}

# Call the function
sayHello
Enter fullscreen mode Exit fullscreen mode

We have just looked at how to create a function but we did not include the parameters in the function. Next, let us look at creating a function with parameters. In this example, the parameters are $1 and $2

Function with Parameters

greet() {
    echo "Hello, I am $1 and I am $2 years old!"
}

# Call the function and pass arguments
greet "Lionel" "26"
Enter fullscreen mode Exit fullscreen mode

The output of this function will be

Hello, I am Lionel and I am 26 years old!
Enter fullscreen mode Exit fullscreen mode

For our last example. Let us look at how to create a folder, and create a file in it. Our folder will be called hello and we will call our file world.

mkdir hello
touch "hello/world.txt"
echo "Hello World" >> "hello/world.txt"
echo "Created hello/world.txt"
Enter fullscreen mode Exit fullscreen mode

Tips for Writing Efficient Shell Scripts

Maximize the efficiency of your shell scripts by following these helpful tips.

  • When it comes to error handling, make sure to include proper error checking and handling mechanisms in your scripts. This will help you identify and address any issues or errors that may occur during the execution of the script.
  • Use conditional statements such as if-else or case statements to check for errors and handle them accordingly.
  • It is also a good practice to use exit codes to indicate the success or failure of a script, allowing you to automate processes based on these codes.

In addition, following best practices is crucial for writing efficient shell scripts.

  • One important tip is to keep your code clean and organized using functions and modularizing your script into smaller, reusable parts. This not only makes your code more readable but also allows for easier maintenance and troubleshooting in the future.
  • Another best practise is to use comments throughout your script to provide explanations and documentations for each step or section of code. This helps other developers (including yourself) understand the purpose and functionality of different parts of the script.

By implementing these tips, you can ensure that your shell scripts are efficient, robust, and easy to maintain over time.

Becoming a Shell Scripting Guru

Developing expertise in shell scripting can empower you to create robust and sophisticated automation solutions. By becoming a Shell Scripting Guru, you gain the ability to utilize various shell scripting tools and apply best practices effectively. These tools include utilities like awk, sed, grep, and cut which enable you to manipulate text data efficiently. With these powerful tools at your disposal, you can easily extract specific information from files or perform complex text processing tasks.

Conclusion

In conclusion, mastering shell scripting is a crucial skill for anyone looking to streamline their automation processes. This article has provided an extensive cheat sheet that covers basic concepts and advanced techniques in shell scripting, ensuring that readers have all the necessary tools at their disposal. By following the tips outlined in this article, such as writing efficient scripts and continuously honing your skills, you can become a shell scripting guru.

The saying practice makes perfect rings true when it comes to shell scripting. It is through continuous practice and experimentation that one can truly become proficient in this field.

In conclusion, with this ultimate cheat sheet as your guide, there's no limit to what you can achieve with shell scripting. So go ahead, embrace the challenge, and let your creativity soar as you embark on your journey towards becoming a shell scripting guru.

Top comments (2)

Collapse
 
michaelsynan profile image
Michael Synan

Cool man good stuff

Collapse
 
softwaresennin profile image
Lionel♾️☁️

Awesoome! Thanks for the comment man ... glad you found it useful.