MoreBash:Exercises - Declare - Typing variables

From Juneday education
Jump to: navigation, search

Work in progress

This chapter is a work in progress. Remove this section when the page is production-ready.

TODO: Write exercises!

Prerequisite knowledge

These exercises assume that you have basic knowledge of Bash, computers and networks. We have books covering some of these basics, if you need to refresh them.

Introduction

The purpose of these exercises is to get you familiar with the declare builtin in bash. See the previous chapter PDF (and if available lecture video) for an introduction to declare. Be sure to read also the external links for further reading of the previous chapter.

Exercises

Task 1 - Array of hosts

Create a script which declares an array variable hosts with a few host names, and tries to ping each one of them.

If a host cannot be pinged, the script should output something like:

Couldn't ping www.apaisnotpingable.com

The script should also write statistics of the number of failed pings.

As a challenge, handle plural in the case of more than one fail so that the script can write either

...
1 host failed

or

2 hosts failed

Expand using link to the right to see a hint.

An array can be declared and initialized like this:

declare -a hosts='(
   [0]=www.chalmers.se
   [1]=www.sunet.se
   [2]=wrongname2.se
   [3]=wrongname3
)'

Or, less verbose:

declare -a hosts=(
 www.chalmers.se
 www.sunet.se
 wrongname2.se
 wrongname3
)

You can write the whole array like this:

echo Checking ping to ${hosts[@]}

You can limit ping to one ping using:

ping -c 1 somehost.somedomain

You can send both stdout and stderr to /dev/null if you don't want to see the output of the ping command:

ping -c 1 somehost.somedomain &> /dev/null

You can use the || to handle the case of a ping error

ping -c 1 somehost.somedomain || echo some error message

You can group things after the || with { command1; command2; }

ping -c 1 somehost.somedomain || { dosometing;dosometingelse; }

You can use a nifty check to handle the plural "s"

((someVariable > 1)) && someString="s"

Expand using link to the right to see a possible solution.

#!/bin/bash

declare -i num_fail=0
declare -a hosts='(
   [0]=www.chalmers.se
   [1]=www.sunet.se
   [2]=wrongname2.se
   [3]=wrongname3
)'
echo Checking ping to ${hosts[@]}
for host in ${hosts[@]}
do
    ping -c 1 $host &>/dev/null || {
        echo "No ping to $host"; ((num_fail++));
    } 
done
suffix=""
((num_fail>1)) && suffix="s"
echo $num_fail failure$suffix

Task 2 - next task...

Next task...

Expand using link to the right to see a hint.

Task 3 -

Next task...

Expand using link to the right to see a hint.

Task 4 -

Next task...

Expand using link to the right to see a hint.

Links

Chapter links

Next page is a new topic: Functions - Introduction.

« PreviousBook TOCNext »