Linux: Window Menu Driven App Example

Linux: Window Menu Driven App Example

In this tutorial, you will learn how to create a window-based menu driven app in Linux using the shell script.

Linux Window-Based Menu Driven App Example

The following bash shell script in Linux will create a dialog box menu to display options such as show calendar, show current date and time, and to show vi editor. You can change the menu options by changing the text in the while loop section and modify the functions accordingly, which are being called on the selection of menu, such as show_calendar(), show_date(), etc.

#!/bin/bash

# Create a file to store the menu
RESPONSE=menu.txt

# Create a file to store the content to display
TEMP_DATA=output.txt

# variable for vi editor to run it directly
vi_editor=vi

# trap and delete temp files
trap "rm $TEMP_DATA; rm $RESPONSE; exit" SIGHUP SIGINT SIGTERM

# below function takes three parameters 1st height, 2nd width, 3rd widnow title
function show_output(){
dialog --backtitle "Menu Driven App" --title "$3" \
--clear --msgbox "$(<$TEMP_DATA)" $1 $2
}

function show_date(){
echo "Today is `date` @ $(hostname -f)." >$TEMP_DATA
show_output 6 60 "Date and Time"
}

function show_calendar(){
cal >$TEMP_DATA
show_output 13 25 "Calendar"
}

# calling infinite loop here
while true
do
# Display main menu
dialog --help-button --clear --backtitle "Menu Driven App" \
--title "[ Dialog Window Menu ]" \
--menu "Please use up/down arrow keys, number keys\n\
1,2,3.., or the first character of choice\n\
as hot key to select an option" 15 50 4 \
Calendar "Show the Calendar" \
Date/time "Show date and time" \
VI-Editor "Start vi editor" \
Exit "Terminate the Script" 2>"${RESPONSE}"
menuitem=$(<"${RESPONSE}")
# Start activity as per selected choice
case $menuitem in
Calendar) show_calendar;;
Date/time) show_date;;
VI-Editor) $vi_editor;;
Exit) echo "Thank you !"; break;;
esac
done
# Delete the temp files
[ -f $TEMP_DATA ] && rm $TEMP_DATA
[ -f $RESPONSE ] && rm $RESPONSE

Output

Linux Menu Driven App

See also: