A Simple Menu Based Linux Shell Script For Finding Out Network Interfaces Related Information

Here is a simple menu based Linux shell script that uses mainly the commands “ifconfig” and “uptime”  to :

  • List all the available network interfaces on the system (like wired adapter/eth0, wireless adapter/wlan0 and so on).
  • List all the information about each of the available network interfaces (like local IP address, subnet mask, if interface is up or down etc.)
  • Show how long the system has been running.

To get a brief overview of what shell scripts are and to get an idea of how this shell script shown works, refer to the primer here.

The script is named as networkinfo.sh. To make it executable, use chmod a+x networkinfo.sh and  finally run it by typing : ./networkinfo.sh

The script code is as follows :

#!/bin/bash
# A simple menu driven script for finding out network info about the system
# Demonstrated for fun by guys at ihaveapc.com

echo " Please select your choice number from below or hit Ctrl-C to exit:"
echo "---------------------------------------------------------------------------------------------"
echo "Press 1 to list all the network interfaces on this system"
echo "Press 2 to find out info about all available network interfaces on this system"
echo "Press 3 to see how long has this computer been up since last reboot"
echo ""

# Read the choice from user and store in variable named choice
read choice

#Use case to match the variable value and do appropriate stuff
case $choice in
1)
echo "Hi $USER"
echo ""
echo "The following network interfaces are found on this system :"
echo "-------------------------------------------------------------"
ifconfig | cut -c-10 | tr -d ' ' | tr -s '\n';;

2)
echo "Hi $USER"
echo ""
echo "Network information for all interfaces found on this system as follows:"
echo "------------------------------------------------------------------------------------------------"
ifconfig;;

3)
echo "Hi $USER"
echo ""
echo "This computer named $HOSTNAME has been up since"
echo "---------------------------------------------------------------------------------"
uptime|awk '{print $1}';;

*) echo "Not a valid choice! Please rerun the script and enter a valid choice between 1 to 3";;
esac

The above script is very similar to an automated response system where by pressing predefined keys or numbers, different information is listed.

Various outputs for each of the choices selected are as shown :

List network interfaces

List interfaces info

Show uptime

Invalid choice when running script

This is a very similar script to the one before which listed computer name, list of logged in users and so on. Check it out here. As always, the cool thing about Linux shell scripts is that various commands can be neatly combined to do something useful without getting too complex like the above script.

Happy scripting.