Book Image

Bash Cookbook

By : Ron Brash, Ganesh Sanjiv Naik
Book Image

Bash Cookbook

By: Ron Brash, Ganesh Sanjiv Naik

Overview of this book

In Linux, one of the most commonly used and most powerful tools is the Bash shell. With its collection of engaging recipes, Bash Cookbook takes you through a series of exercises designed to teach you how to effectively use the Bash shell in order to create and execute your own scripts. The book starts by introducing you to the basics of using the Bash shell, also teaching you the fundamentals of generating any input from a command. With the help of a number of exercises, you will get to grips with the automation of daily tasks for sysadmins and power users. Once you have a hands-on understanding of the subject, you will move on to exploring more advanced projects that can solve real-world problems comprehensively on a Linux system. In addition to this, you will discover projects such as creating an application with a menu, beginning scripts on startup, parsing and displaying human-readable information, and executing remote commands with authentication using self-generated Secure Shell (SSH) keys. By the end of this book, you will have gained significant experience of solving real-world problems, from automating routine tasks to managing your systems and creating your own scripts.
Table of Contents (15 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Writing high-quality scripts by example


In this recipe, we are going to see functions in shell scripts. We will see how our program testing is done, sequentially on the various parts, using functions. Functions help improve the readability of a program.

 

Getting ready

Besides having a terminal open, you need to have a basic knowledge of functions.

How to do it...

We are going to write a simple function in our shell script to return the current date and time. Create a script function_example.sh, and write this code in it:

#!/bin/bash
print_date()
{
echo "Today is `date`"
return
}
print_date

Now we will create another script containing two functions with the same name. Create a script function2.sh, and write the following content in it.

#!/bin/bash
display ( ) {
echo 'First Block'
echo 'Number 1'
}
display ( ) {
echo 'Second Block'
echo 'Number 2'
}
display
exit 0

How it works...

In the first script, we created a function named print_date() and we just printed a date using a function.

In the second...