November 5, 2024

Here is a useful bash shell script which uses a menu driven user input and will display the following info :

  • Your computer name
  • List of users who have logged in
  • Total disk space usage
  • List of files and folders in your home directory.

Think of it as the automated response system (press 1 for A, press 2 for B and so on).

Here is the code (script is named as info.sh) :

#!/bin/bash
# A simple menu driven script for user and system info
# Demonstrated for fun by guys at ihaveapc.com
# User menu with choices

echo " Please select your choice number from below or hit Ctrl-C to exit:"
echo "--------------------------------------------------------------------"
echo "Press 1 to find out your system name"
echo "Press 2 to find out your disk space usage"
echo "Press 3 to see who is currently logged in"
echo "Press 4 to list the contents of your home directory"

# 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 "Your computer name is :"
echo "-----------------------"
hostname;;

2)
echo "Disk space usage is"
echo "-------------------------"
df -h;;

3)
echo "Currently logged in users are"
echo "-----------------------------"
who;;

4)
echo "Hi $USER, the contents of your home directory are :"
ls -ltr /home/$USER;;

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

Make it executable (sudo chmod a+x info.sh) and run it (./info.sh) to have fun.

It uses the case statement to evaluate user choices and run appropriate commands. (You can try to refine it by bringing the main menu back once a valid choice is executed.)

Here are the outputs :

If you enter an invalid choice, your system will shut down and you will lose your unsaved work (that was a joke but you can do it 😉 ) :

Cheers.

[ For understanding the basics of shell scripting primer, start from here. ]

By admin

Related Post

One thought on “A Simple Menu Driven Linux Shell Script For Finding Out Computer Name And Other Cool Stuff”

Comments are closed.