Book Image

Mastering Bash

By : Giorgio Zarrelli
Book Image

Mastering Bash

By: Giorgio Zarrelli

Overview of this book

System administration is an everyday effort that involves a lot of tedious tasks, and devious pits. Knowing your environment is the key to unleashing the most powerful solution that will make your life easy as an administrator, and show you the path to new heights. Bash is your Swiss army knife to set up your working or home environment as you want, when you want. This book will enable you to customize your system step by step, making your own real, virtual, home out of it. The journey will take you swiftly through the basis of the shell programming in Bash to more interesting and challenging tasks. You will be introduced to one of the most famous open source monitoring systems—Nagios, and write complex programs with it in any languages. You’ll see how to perform checks on your sites and applications. Moving on, you’ll discover how to write your own daemons so you can create your services and take advantage of inter-process communication to let your scripts talk to each other. So, despite these being everyday tasks, you’ll have a lot of fun on the way. By the end of the book, you will have gained advanced knowledge of Bash that will help you automate routine tasks and manage your systems.
Table of Contents (15 chapters)

The for loop

The for loop is one of the most used structures when it comes to a Bash script and enables us to repeat one of more actions on each single item in a list. Its basic structure can be outlined as follows:

for placeholder in list_of_items
do
action_1 $placeholder
action_2 $placeholder
action_n $placeholderdone

So, we use a placeholder, which will take at each round of the loop one of the values in the list of items, which will then be processed in the do section. Once all the list is scanned through, the loop is done, and we exit it. Let's start with a simple and nice example:

#!/bin/bash
for i in 1 2 3 4 5
do
echo "$i"done

And now let's execute it:

zarrelli:~$ ./counter-simple.sh 
1
2
3
4
5

Actually, quite straightforward, but notice that the list can be the result of any kind of operations:

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

In...