Saturday, 10 December 2016

Using select to create menu driven shell scripts


Menu driven scripts are an important aspect to consider when writting large scripts which would require user input for further processing. We can use an infinite while loop to create a menu for a shell script & that is quite common. If you have an X windows system available then you can make use of dialog or whiptail to create nice menus & dialog boxes for your scripts. In this article I'll domonstrate how we can use the select command for creating simple menu driven scripts.

The syntax for select command is:

select var in list
do
    commands..
done

The select command runs an inifinite loop. var is the variable you'd use in your case statement for the menu. The list would be the menu options. The commands would be part of the case statements being issued during the execution of the menu selection.
We can write the commands to be executed for a menu selection within the select loop but for a cleaner code I'll write the commands within separate functions & just call the functions in the case statements within the select loop.

So, here is the example script:

root@buntu:~# cat select.sh
#!/bin/bash

trap '' 2  # ignore ctrl+c

##set PS3 prompt##
PS3="Enter your selection: "

function diskspace {
        df -h
}

function users {
        who
}

select opts in "check disk usage" "check users" "exit script"
do
        case $opts in
                "check disk usage")
                                echo -e "\e[0;32m $(diskspace) \e[m"
                                ;;
                "check users")
                                echo -e "\e[0;32m $(users) \e[m"
                                ;;
                "exit script")
                                break
                                ;;
                *)
                                 echo "invalid option"
                                ;;
        esac
done


The script when executed will present three options to the user. Selecting option 1 will call the diskspace function, option 2 will the users function & option 3 will exit out of the loop.
I've added a trap to ignore ctrl+c presses or the INT signal & added some color to the output. 


1 comment:

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...