Creating shell context menu

Create a text menu

The core is the case command to execute specific commands based on the user's choice.

Create a menu layout

Use the echo command to print characters, generates a menu, you can also include information such as title:

clear
echo
# -e 选项,打印特殊字符
echo -e "\t\t\tSys Admin Menu\n"
echo -e "\t1. Display disk space"
echo -e "\t2. Display logged on users"
echo -e "\t3. Display memory usage"
echo -e "\t0. Exit program\n\n"
# -en 会去掉末尾的换行符,光标会留在行尾
echo -en "\t\tEnter option: "
# 获取用户输入,只期望获取到单个字符,-n选择限制只读1个字符,并且用户不用回车
read -n 1 option

clear command to clear the contents of the current session.
echo -e option, you can print special characters.
echo -en option will remove line breaks at the end. This makes the menu look more professional, the cursor will always end of the line waiting for user input.

Get User Input
After printing out the menu, we must wait and get user input. This is done with the read command. Here desirable as long as a single character, so use the -n option to read only one character limit. So users only need to enter a number and do not press Enter.

Create a menu function
the top portion of the package into a function, so that at any time as long as the function is called will be able to reproduce the menu.

Creating stubs

Stubs (stub function), is an empty function, or only one echo statement, explain what eventually need here:

function diskspace {
    clear
    echo "Display disk space"
}

In this way, you do not need all the functions written in advance. Menu can be directly put into use after to achieve a specific operation.

Add menu logic

Menu layout and function have it all, we need to create the following program logic to combine the two. Here it is necessary case command.
case commands based on the character input menu to call the appropriate function. Use the default command character asterisk case to handle all incorrect menu item.
Here is the complete menu script examples:

#!/bin/bash
# 为脚本创建文本菜单

# --------------------
# 定义函数
# --------------------

# 打印菜单
function menu {
    clear
    echo
    # -e 选项,打印特殊字符
    echo -e "\t\t\tSys Admin Menu\n"
    echo -e "\t1. Display disk space"
    echo -e "\t2. Display logged on users"
    echo -e "\t3. Display memory usage"
    echo -e "\t0. Exit program\n\n"
    # -en 会去掉末尾的换行符,光标会留在行尾
    echo -en "\t\tEnter option: "
    # 获取用户输入,只期望获取到单个字符,-n选择限制只读1个字符,并且用户不用回车
    read -n 1 option
}

function diskspace {
    clear
    df -k
}

function whoseon {
    clear
    who
}

function menusage {
    clear
    cat /proc/meminfo
}

# --------------------
# 函数主体
# --------------------
while [ 1 ]
do
    # 菜单逻辑
    menu
    case $option in
    0)
        break ;;
    1)
        diskspace ;;
    2)
        whoseon ;;
    3)
        menusage ;;
    *)
        clear
        echo "Wrong selection";;
    esac
    echo -en "\n\n\t\tHit any key to continue"
    read -n 1 line
done
clear

Menu display is as follows:


                        Sys Admin Menu

        1. Display disk space
        2. Display logged on users
        3. Display memory usage
        0. Exit program

                Enter option: 

Use the select command

The process of creating a text menu, it took half the energy on the establishment of the menu layout and get user input. bash shell provides a very easy to use small tools that can help automate these tasks.

select command requires only one command can create a menu, and then get the input and automatically processed. Command format is as follows:

select 选项变量 in "选项1" "选项2" "选项3"
do
    命令
done

select each option will automatically add the command number, then displays a special prompt PS3 defined by the environment variable options. So PS3 also define an environment variable.

Sample Code

Here is an example of a select command:

#!/bin/bash
# 为脚本创建文本菜单

function diskspace {
    clear
    df -k
}

function whoseon {
    clear
    who
}

function menusage {
    clear
    cat /proc/meminfo
}

PS3="Enter option: "
select option in "Display disk space" "Display logged on users" \
"Display memory usage" "Exit program"
do
    case $option in
    "Exit program")
        break ;;
    "Display disk space")
        diskspace ;;
    "Display logged on users")
        whoseon ;;
    "Display memory usage")
        menusage ;;
    *)
        clear
        echo "Wrong selection";;
    esac
done

Menu effect is as follows:

$ menu2.sh 
1) Display disk space           3) Display memory usage
2) Display logged on users  4) Exit program
Enter option: 

Using this tool you can quickly create a simple menu, but the visual effect is a lot worse.

Production window (dialog package)

dialog package can create a standard text in an environment with ANSI escape control characters in a window box.

Widget

package provides many dialog window member (widget), when using the command format is as follows:

dialog --widget parameters

Commonly used components as follows:

  1. msgbox member: display a simple message in the window, there is an OK button
  2. yesno member: Allows the user to issue a display window select yes or no, there will be two buttons
  3. inputbox member: a simple text box to enter text region
  4. textbox member: large amount of information can be displayed in the window, it will generate a rolling window
  5. menu components: create a text menu, select the need to provide a label and text for each option
  6. fselect components: can be used to browse files and folders

More widgets, listed in more detail later.

Acquiring output member

Each dialog means provide two forms of output:

  • Use the exit status codes
  • Use STDERR

Return to the Options
If you select YES or OK, return the exit code of 0. If you select Cancel or No, return the exit code 1. You can use the standard $? Variable to determine specifically which button is selected.

Return data
if the data is returned, it will be sending data to STDERR. Using standard methods to a bash shell STDERR redirect output to file or another file descriptor:

dialog --inputbox "Enter your age: " 10 20 2>age.txt

Specifically how to use can refer to the following examples.

Sample Code

More content, not necessarily feel the need to make such a good window to exchange. Remember two things when writing the script:

  • If there is a button, check the exit status of the command dialog
  • Otherwise redirect STDERR to get the value of output

Examples of dialog preceding example code implementation of the package:

#!/bin/bash
# 为脚本创建文本窗口菜单

temp=$(mktemp -t test.XXXXXX)
temp2=$(mktemp -t test2.XXXXXX)

function diskspace {
    df -k > $temp
    dialog --textbox $temp 20 60
}

function whoseon {
    who > $temp
    dialog --textbox $temp 20 50
}

function menusage {
    cat /proc/meminfo > $temp
    dialog --textbox $temp 20 50
}

while [ 1 ]
do
dialog --menu "Sys Admin Menu" 20 30 10 \
1 "Display disk space" \
2 "Display logged on users" \
3 "Display memory usage" \
0 "Exit program" 2> $temp2
if [ $? -eq 1 ]
then
    break
fi

selection=$(cat $temp2)
case $selection in
0)
    break ;;
1)
    diskspace ;;
2)
    whoseon ;;
3)
    menusage ;;
*)
    dialog --msgbox "Wrong selection" 10 30
esac
done
rm -f $temp 2> /dev/null
rm -f $temp2 2> /dev/null

This uses temporary files, and use the mktemp command to create a temporary file, looking very professional.

Package installation dialog

In addition the system may not installed by default dialog package, to run this script, you need to install dialog package:

[root@Ansible ~]# yum info dialog
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
已安装的软件包
名称    :dialog
架构    :x86_64
版本    :1.2
发布    :5.20130523.el7
大小    :505 k
源    :installed
来自源:base
简介    : A utility for creating TTY dialog boxes
网址    :http://invisible-island.net/dialog/dialog.html
协议    : LGPLv2
描述    : Dialog is a utility that allows you to show dialog boxes (containing
         : questions or messages) in TTY (text mode) interfaces.  Dialog is called
         : from within a shell script.  The following dialog boxes are implemented:
         : yes/no, menu, input, message, text, info, checklist, radiolist, and
         : gauge.
         : 
         : Install dialog if you would like to create TTY dialog boxes.

dialog detailed table member

dialog member

component description
calendar Provide selected date calendar
checklist Multiple display options (each option can be turned on or off)
form Build a form with a label and text field (you can fill in the content) of
fselect A file selection window to browse to the file
gauge The progress bar displays the percentage of completion
infobox A message appears, but do not wait for a response
inputbox Provide a text input with text form
inputmenu It provides an editable menu
menu Display a series of selectable options
msgbox Displays a message and requires the user to select the OK button
pause A progress bar to show the state during pauses
PasswordBox A text box, but hidden text input
passwordform x ranch with a form tag and hidden text field
radiolist Provides a set of menu options, select only a single one of them. It is the radio
tailbox Display the contents of a file in a scrollable window with the tail command
tailboxbg More tailbox the same, but running in the background mode
textbox Display the contents of a file in a scrollable window
timebox A choice hour, minute, and second window
yesno Providing a simple message with Yes and No buttons

Options dialog

In addition to standard components, you can also customize different options in the dialog command. These options allow you to fully customize the appearance and operation of the window.

Command Options dialog

Options description
--add-widget Continue to the next dialog until you press Esc or Cancel button
--aspect ratio Specified window width and height aspect ratio
--backtitle title Specify the title on the top of the screen background display
--begin x y Upper left corner of the specified window starting position
--clear Dialogue with the default background color to clear the screen content
--colors ANSI color coding embedded in the text dialogue
--cr-wrap In the dialog allows text to use line breaks and force a line break
--create-rc file Copy the contents of the sample configuration file to the specified file file
--default-item string Set the default item check list, form or menu dialogue
--help Display help information dialog command
--help-status When the Help button is selected, a list of multiple choice written after the help information, the radio list or form information
--ignore Ignore dialog does not recognize the options
--input-fd fd Another addition to the specified file descriptors STDIN
--insecure When the asterisk is displayed in the password typing member
--item-help A multi-selection list, a radio list or menu of each label to add a help bar at the bottom of the screen
--keep-window Do not clear the display on the screen over parts
--max-input size Specify the maximum length of the input string. The default is 2048
--no-collapse Do not convert the text in dialog tabs to spaces
--no-kill The tailbox dialog box in the background, and prohibit the process SIGHUP signal
--no-shadow Do not show shadows of the dialog window
--output-fd fd Another specified output file descriptor other than the STDERR
--print-maxsize The maximum size of the dialog window to print output
--print-size The size of the print dialog window size to the output
--print-version The dialog version number to print output
--separate-output Results one row checklist output member, without quotes
--separator string Means for separating the specified string output
--separate-widget string Means for separating the specified string output
--shadow Draw shadow in the lower right corner of each window
--single-quoted When the output required for multiple-selection list of single quotation marks
--sleep sec Delay specified number of seconds after handling dialog window
--stderr The output is sent to STDERR (default behavior)
--stdout Sending output to STDOUT
--tab-correct 将制表符转换成空格
--tab-len n 指定一个制表符占用的空格数(默认为8)
--timeout sec 指定无用户输入时,sec秒后退出并返回错误代码
--titel title 指定对话窗口的标题
--trim 从对话文本中删除前导空格和换行符
--visit-items 修改对话窗口中制表符的停留位置,使其包括选项列表

dialog命令选项2
按钮的选项功能都差不多,单独列出在这里。可以重写对话窗口中的任意按钮标签:

选项 描述
--cancel-label label 指定Cancel按钮的替代标签
--defaultno 将yes/no对话框的默认答案设为No
--exit-label label 指定Exit按钮的替代标签
--extra-button 在OK按钮和Cancel按钮之间显示一个额外按钮
--extra-label label 指定额外按钮的替代标签
--help-button 在OK按钮和Cancel按钮后显示一个Help按钮
--help-label label 指定Help按钮的替代标签
--nocancel 隐藏Cancel按钮
--no-lable label 为No按钮指定替代标签
--ok-label label 指定OK按钮的替代标签
--yes-label label 为Yes按钮指定替代标签

举例说明

  • --title选项,允许你设置出现在窗口顶部的部件标题。
  • --backtitle选项,是为脚本中的菜单创建公共标题的简便办法。
  • --create-rc选项,dialog命令支持运行时配置。该命令会根据配置文件模板创建一份配置文件。

创建本地临时文件(mktemp)

在需要临时将内容保存到文件的时候,有个特殊命令可以用来创建临时文件。mktemp命令可以在/tmp目录中创建一个唯一的临时文件。shell会创建这个文件,但不用默认的umask值。它会将当前用户设置为文件的属主,并且只有属主有读写权限。

创建文件

默认情况下,mktemp会在当前目录中创建一个文件。使用命令的时候,需要指定一个文件名模板。模板可以包含任意文本文件名,在文件名末尾加上6个X(几个X都没关系,书上建议6位):

$ mktemp test1.XXXXXX
test1.Acrugq
$ ls -al test1*
-rw-------. 1 steed steed 0 12月 12 14:26 test1.Acrugq
$ 

mktemp命令会用6位字符码替换这6个X,从而保证文件名在目录中是唯一的。

在脚本中使用

在脚本中使用mktemp命令时,需要将文件名保存到变量中,这样就能在后面的脚本中引用了:

$ mktemp test2.XXXXXX
test2.leOFBZ
$ mktemp test2.XXXXXX
test2.5kDbKn
$ mktemp test2.XXXXXX
test2.domeOC
$ mktemp test2.XXXXXX
test2.CJX702
$ tempfile=$(mktemp test2.XXXXXX)
$ exec 3>>$tempfile
$ echo "test2 Line1" >&3
$ echo "TEST2 LINE2" >&3
$ exec 3>&-
$ cat $tempfile
test2 Line1
TEST2 LINE2
$ ls -al test2*
-rw-------. 1 steed steed  0 12月 12 14:41 test2.5kDbKn
-rw-------. 1 steed steed  0 12月 12 14:41 test2.CJX702
-rw-------. 1 steed steed  0 12月 12 14:41 test2.domeOC
-rw-------. 1 steed steed  0 12月 12 14:41 test2.leOFBZ
-rw-------. 1 steed steed 24 12月 12 14:41 test2.tMVTwN
$ rm -f $tempfile 2> /dev/null
$ ls -al test2*
-rw-------. 1 steed steed 0 12月 12 14:41 test2.5kDbKn
-rw-------. 1 steed steed 0 12月 12 14:41 test2.CJX702
-rw-------. 1 steed steed 0 12月 12 14:41 test2.domeOC
-rw-------. 1 steed steed 0 12月 12 14:41 test2.leOFBZ
$ 

这里先创建了几个临时文件,干扰一下。使用的时候,创建了文件描述符3来使用,使用完之后关闭了文件描述符。最后精确的把用完的临时文件给删除了。

在/tmp目录创建临时文件

-t选项会强制mktemp命令在系统的临时目录创建文件。此时返回的就是创建的文件的全路径:

$ mktemp -t test3.XXXXXX
/tmp/test3.aPIXIy
$ 

创建临时目录

-d选项则是创建一个临时目录。如果要在/tmp目录下创建临时目录,就是-dt:

$ mktemp -d dir.XXXXXX
dir.aBDmsd
$ mktemp -dt dir.XXXXXX
/tmp/dir.pqW927
$ 

Guess you like

Origin blog.51cto.com/steed/2458047