Book Image

Mastering Linux Shell Scripting - Second Edition

By : Mokhtar Ebrahim, Andrew Mallett
5 (1)
Book Image

Mastering Linux Shell Scripting - Second Edition

5 (1)
By: Mokhtar Ebrahim, Andrew Mallett

Overview of this book

In this book, you’ll discover everything you need to know to master shell scripting and make informed choices about the elements you employ. Grab your favorite editor and start writing your best Bash scripts step by step. Get to grips with the fundamentals of creating and running a script in normal mode, and in debug mode. Learn about various conditional statements' code snippets, and realize the power of repetition and loops in your shell script. You will also learn to write complex shell scripts. This book will also deep dive into file system administration, directories, and system administration like networking, process management, user authentications, and package installation and regular expressions. Towards the end of the book, you will learn how to use Python as a BASH Scripting alternative. By the end of this book, you will know shell scripts at the snap of your fingers and will be able to automate and communicate with your system with keyboard expressions.
Table of Contents (17 chapters)

Extending if with else

When a script is required to continue regardless of the result of the if condition, it is often necessary to deal with both conditions of the evaluation, what to do when it is true as well as false. This is where we can make use of the else keyword. This allows the execution of one block of code when the condition is true and another when the condition is evaluated as false. The pseudocode for this is shown as follows:

if condition; then 
   statement 
else  
   statement 
fi 

If we consider extending the hello5.sh script that we created earlier, it is easily possible to allow for the correct execution, regardless of the parameter being present or not. We can recreate this as hello6.sh, as follows:

#!/bin/bash 
# Welcome script to display a message to users 
# Author: @theurbanpenguin 
# Date: 1/1/1971 
if [ $# -lt 1 ] ; then 
read -p "Enter a name...