In this lecture, I'll show you an example of a script that uses command substitution, string testing 1
and an if statement to check the network connection between the local machine and the remote one. 2
Just imagine that you want your local machine, which could be a server, to continuously check the network 3
connection to the default gateway or another machine on your lan or on the Internet. 4
If the connection is down, the script will inform the admin with an email message or even change the 5
network configuration like say, changing the default gateway 6
if there are more Internet connections available. I'm creating a new script: connection_testing 7
The ip address of the remote system will be the first argument of the script, and as you already know 8
it's $1. I'm sending three ping packets to that IP address and taking the output of the ping command 9
in a variable using a command substitution. 10
So output ="$(ping -c 3 $1)" 11
Let's test the script up until this point; itis always a good idea 12
to test your scripts as to develop them. This way 13
you avoid writing tens of lines of code 14
just realize at the end that everything was wrong. 15
So echo $output 16
So connection_testing and an IP address 8.8.8.8 17
And this is the output: zero percentage packet loss. By the way, if you want to see the output on multiple 18
lines, like the output of the command when it's run in the terminal, enclose the variable in double 19
quotes. 20
Now, I'll run the script with an IP address as argument that will fail 1.2 3.4. 21
OK, one hundred percent packet loss! We see the substring 100% packet loss, so you can search 22
for that substring in the output. There are more approaches 23
but I'll use the simplest one. 24
I'll check if the substring is contained in the output variable. 25
So if [[ $output == *"100% packet loss"* ]] 26
I'm copying and pasting the substring. 27
If the condition is true, then echo "The network connection to $1 is not working." 28
else 29
If the substring is not contained, echo "the network connection is working." 30
So connection_testing and the working I.P. address 8.8.8.8. 31
The network connection to 8.8.8.8. is working. 32
And this time to a nonexisting IP address or an IP address, which is down. I suppose this IP address 33
is down. 34
And they've got the correct message. That's great!