Creating operator menus

We can provide a menu to the Linux operators who need limited functionality from the shell and do not want to learn the details of command line use. We can use their login script to launch a menu for them. This menu will provide a list of command selections to choose from. The menu will loop until the user chooses to exit from the menu. We can create a new $HOME/bin/menu.sh script, the basis of the menu loop will be the following:

while true
do
……
done

The loop we have created here is infinite. The true command will always return true and loop continuously; however, we can provide a loop control mechanism to allow the user to leave the menu. To start building the structure of the menu, we will need to echo some text within the loop asking the user for their choice of command. We will clear the screen before the menu is loaded each time and an additional read prompt will appear after the execution of the desired command.

This allows the user to read the output from the command before the screen is cleared and the menu is reloaded. The script will look like the following code at this stage:

#!/bin/bash
# Author: @theurbanpenguin
# Web: www.theurbapenguin.com
# Sample menu
# Last Edited: August 2015

while true
do
  clear
  echo "Choose an item: a,b or c"
  echo "a: Backup"
  echo "b: Display Calendar"
  echo "c: Exit"
  read -sn1
  read -n1 -p "Press any key to continue"
done

If you execute the script at this stage, there will be no mechanism to leave the script. We have not added any code to the menu selections; however, you can test functionality and exit using the Ctrl + c key.

At this stage the menu should look similar to the output shown in the following screenshot:

Creating operator menus

To build the code behind the menu selection, we will implement a case statement. This will be added in between the two read commands, as follows:

read -sn1
  case "$REPLY" in
    a) tar -czvf $HOME/backup.tgz ${HOME}/bin;;
    b) cal;;
    c) exit 0;;
  esac
  read -n1 -p "Press any key to continue"

We can see the three options that we have added to the case statement, a, b, and c:

  • Option a: This runs the tar command to back-up the scripts
  • Option b: This runs the cal command to display the current month
  • Option c: This exits the script

To ensure that the user is logged out when exiting from their login script, we will run:

exec menu.sh

The exec command is used to ensure that the shell is left after the menu.sh file is complete. In this way, the user never needs to experience the Linux shell. The complete script is shown in the following screenshot:

Creating operator menus
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.13.192