Include trap statements in a script

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← How to clear trapHomeUse the trap statement to catch signals and handle errors →

You can use the trap command in shell script as follows. Create a shell script called mainmenu01.sh:

#!/bin/bash
 
# capture CTRL+C, CTRL+Z and quit singles using the trap
trap 'echo "Control-C disabled."' SIGINT
trap 'echo "Cannot terminate this script."'  SIGQUIT
trap 'echo "Control-Z disabled."' SIGTSTP
 
# Create infinite while loop
while true
do
    clear
    # display menu
    echo "Server Name - $(hostname)"
	echo "-------------------------------"
	echo "     M A I N - M E N U"
	echo "-------------------------------"
	echo "1. Display date and time."
	echo "2. Display what users are doing."
	echo "3. Display network connections."
	echo "4. Exit"
 
    # get input from the user 
	read -p "Enter your choice [ 1 -4 ] " choice
 
    # make decision using case..in..esac 
	case $choice in
		1)
			echo "Today is $(date)"
			read -p "Press [Enter] key to continue..." readEnterKey
			;;
		2) 
			w	
			read -p "Press [Enter] key to continue..." readEnterKey
			;;
		3)
			netstat -nat
			read -p "Press [Enter] key to continue..." readEnterKey
			;;
		4)
			echo "Bye!"
			exit 0
			;;
		*)
			echo "Error: Invalid option..."	
			read -p "Press [Enter] key to continue..." readEnterKey
			;;
	esac		
 
done

Save and close the file. Run it as follows:

chmod +x mainmenu01.sh
./mainmenu01.sh

Sample outputs:

Server Name - vivek-desktop
-------------------------------
     M A I N - M E N U
-------------------------------
1. Display date and time.
2. Display what users are doing.
3. Display network connections.
4. Exit
Enter your choice [ 1 -4 ] ^CControl-C disabled.
^ZControl-Z disabled.
1
Today is Wed Sep 23 00:26:38 IST 2009
Press [Enter] key to continue...
Server Name - vivek-desktop
-------------------------------
     M A I N - M E N U
-------------------------------
1. Display date and time.
2. Display what users are doing.
3. Display network connections.
4. Exit
Enter your choice [ 1 -4 ] 4
Bye!
← How to clear trapHomeUse the trap statement to catch signals and handle errors →