Command line dialog window in Linux

Let’s build a radio list for user to enter his choice while running a bash script at Linux command line. We will use the dialog utility for that.

#! /bin/bash

# Define array of choices
choices=(Red Green Blue)

# Construct a dialog and read user's choice
# Dimensions are: Height Width InnerHeight
choice_picked=$(dialog --backtitle "Colour selection" --radiolist "Pick one:" 10 30 3 \
 1 "Bright Red" on \
 2 "Vivid Green" off \
 3 "Dark Blue" off 2>&1 >/dev/tty )

# What was the outcome? Did we get the choice or it all was cancelled?
# 0 if we got the choice; 1 if "Cancel" was selected; 255 if Esc key was pressed
outcome=$?

# Just print the variables
printf "Operation outcome: $outcome\n"
printf "Choice picked: $choice_picked\n"

# Substract 1 because the array index is zero based
selection=${choices[choice_picked - 1]}

# Do something depending upone the resturned values
# In this case - if user selected something, then print it, 
# otherwise just do nothing
case $outcome in
  0)
    printf "Selected value: $selection\n"
    case "$selection" in
        Red)
        printf "Selected value was RED\n";;
        Green)
        printf "Selected value was GREEN\n";;
        Blue)
        printf "Selected value was BLUE\n";;
    esac    
    ;;
  1)
    printf "Cancel\n";;
  255)
    printf "Esc\n";;
esac
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s