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

Gathering network information and connectivity diagnostics


In this section, we are going to test IPv4's connectivity and write scripts for it.

Getting ready

Besides having a terminal open, we need to remember a few concepts:

  • The If..Else condition case in shell scripting
  • IP address of the device
  • curl command must be installed (you can install it by using the following command: sudo apt install curl)

The purpose of this section is to show you how you can check network connectivity.

How to do it...

  1. Open a terminal and create the test_ipv4.sh script:
if ping -q -c 1 -W 1 8.8.8.8 >/dev/null; then
  echo "IPv4 is up"
else
  echo "IPv4 is down"
fi
  1. Now, to test IP connectivity and DNS, create a script called test_ip_dns.sh:
if ping -q -c 1 -W 1 google.com >/dev/null
then
  echo "The network is up"
else
  echo "The network is down"
fi
  1. Lastly, create a script called test_web.sh to test web connectivity:
case "$(curl -s --max-time 2 -I http://google.com | sed 's/^[^ ]*  *\([0-9]\).*/\1/; 1q')" in
  [23]...