Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Bash Cookbook

You're reading from   Bash Cookbook Leverage Bash scripting to automate daily tasks and improve productivity

Arrow left icon
Product type Paperback
Published in Jul 2018
Publisher Packt
ISBN-13 9781788629362
Length 264 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Ganesh Sanjiv Naik Ganesh Sanjiv Naik
Author Profile Icon Ganesh Sanjiv Naik
Ganesh Sanjiv Naik
Ron Brash Ron Brash
Author Profile Icon Ron Brash
Ron Brash
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Crash Course in Bash FREE CHAPTER 2. Acting Like a Typewriter and File Explorer 3. Understanding and Gaining File System Mastery 4. Making a Script Behave Like a Daemon 5. Scripts for System Administration Tasks 6. Scripts for Power Users 7. Writing Bash to Win and Profit 8. Advanced Scripting Techniques 9. Other Books You May Enjoy

Case/switch statements and loop constructs

Besides if and else statements, Bash offers case or switch statements and loop constructs that can be used to simplify logic so that it is more readable and sustainable. Imagine creating an if statement with many elif evaluations. It would become cumbersome!

#!/bin/bash
VAR=10

# Multiple IF statements
if [ $VAR -eq 1 ]; then
echo "$VAR"
elif [ $VAR -eq 2]; then
echo "$VAR"
elif [ $VAR -eq 3]; then
echo "$VAR"
# .... to 10
else
echo "I am not looking to match this value"
fi
In a large number of blocks of conditional logic of if and elifs, each if and elif needs to be evaluated before executing a specific branch of code. It can be faster to use a case/switch statement, because the first match will be executed (and it looks prettier).

Basic case statement

Instead of if/else statements, you can use case statements to evaluate a variable. Notice that esac is case backwards and is used to exit the case statement similar to fi for if statements.

Case statements follow this flow:

case $THING_I_AM_TO_EVALUATE in
  1) # Condition to evaluate is number 1 (could be "a" for a string too!)
echo "THING_I_AM_TO_EVALUATE equals 1"
;; # Notice that this is used to close this evaluation
*) # * Signified the catchall (when THING_I_AM_TO_EVALUATE does not equal values in the switch)
echo "FALLTHOUGH or default condition"
esac # Close case statement

The following is a working example:

#!/bin/bash
VAR=10 # Edit to 1 or 2 and re-run, after running the script as is.
case $VAR in 1)
echo "1"
;;
2)
echo "2"
;;
*)
echo "What is this var?"
exit 1 esac

Basic loops

Can you imagine iterating through a list of files or a dynamic array and monotonously evaluating each and every one? Or waiting until a condition was true? For these types of scenarios, you may want to use a for loop, a do while loop, or an until loop to improve your script and make things easy. For loops, do while loops, and until loops may seem similar, but there are subtle differences between them.

For loop

The for loop is usually used when you have multiple tasks or commands to execute for each of the entries in an array or want to execute a given command on a finite number of items. In this example, we have an array (or list) containing three elements: file1, file2, and file3. The for loop will echo each element within FILES and exit the script:

#!/bin/bash

FILES=( "file1" "file2" "file3" )
for ELEMENT in ${FILES[@]}
do
echo "${ELEMENT}"
done

echo "Echo\'d all the files"

Do while loop

As an alternative, we have included the do while loop. It is similar to a for loop, but better suited to dynamic conditions, such as when you do not know when a value will be returned or performing a task until a condition is met. The condition within the square brackets is the same as an if statement:

#!/bin/bash
CTR=1
while [ ${CTR} -lt 9 ]
do
echo "CTR var: ${CTR}"
((CTR++)) # Increment the CTR variable by 1
done
echo "Finished"

Until loop

For completeness, we have included the until loop. It is not used very often and is almost the same as a do while loop. Notice that its condition and operation is consistent with incrementing a counter until a value is reached:

#!/bin/bash
CTR=1
until [ ${CTR} -gt 9 ]
do
echo "CTR var: ${CTR}"
((CTR++)) # Increment the CTR variable by 1
done
echo "Finished"
You have been reading a chapter from
Bash Cookbook
Published in: Jul 2018
Publisher: Packt
ISBN-13: 9781788629362
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image