Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Shell create text menu

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Create a text menu

The core is the case command, which executes specific commands according to the user's choice.

Create a menu layout

Use the echo command to print characters, generate a menu, and include information such as title:

Clearecho#-e option to print the special character 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 "#-en will remove the newline character at the end of the line, and the cursor will be left at the end of the line echo-en"\ t\ tEnter option: "# to get user input, expecting only a single character,-n option to limit reading to 1 character, and the user does not have to enter read-n 1 option

The clear command first clears the contents of the current session.

Echo-e option, you can print special characters.

The echo-en option removes the newline character at the end. This makes the menu look more professional, and the cursor waits for user input at the end of the line.

Get user input

After printing out the menu, you have to wait and get user input. This step uses the read command. You expect only a single character here, so use the-n option to limit reading to only one character. In this way, the user only needs to enter a number and does not have to press enter.

Create menu function

Encapsulate the above into a function so that the menu can be reproduced whenever the function is called.

Create pile function

The pile function (stub function), which is an empty function, or just an echo statement, indicates what is ultimately needed here:

Function diskspace {clear echo "Display diskspace"}

In this way, there is no need to write all the functions in advance. The menu can be put into use directly, and then the specific operation will be implemented later.

Add menu logic

Now that you have the menu layout and functions, you need to create program logic to combine the two. The case command is needed here.

The case command calls the corresponding function based on the characters entered in the menu. Use the default case command character asterisk to handle all incorrect menu items.

Here is an example of this complete menu script:

#! / bin/bash# create text menu for script #-# define function #-# print menu function menu {clear echo #-e option, print the special character 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 will remove the newline character at the end of the line, and the cursor will be left at the end of the line echo-en"\ t\ tEnter option: "# to get user input, expecting only a single character, and the-n selection limit to 1 character. And the user does not need to enter read-n 1 option} function diskspace {clear df-k} function whoseon {clear who} function menusage {clear cat / proc/meminfo} #-# function body #-while [1] do # menu logic 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 linedoneclear

The menu is displayed as follows:

Sys Admin Menu 1. Display disk space 2. Display logged on users 3. Display memory usage 0. Exit program Enter option: using the select command

In the process of creating a text menu, half the effort is spent on setting up the menu layout and getting user input. Bash shell provides an easy-to-use gadget to help automate these tasks.

The select command only needs one command to create a menu, then take the input and process it automatically. The format of the command is as follows:

Select option variable in "option 1"option 2"option 3" do Command done

The select command automatically numbers each option and displays a special prompt defined by the PS3 environment variable for the option. So you also define the PS3 environment variable.

Sample code

Here is an example of the select command:

#! / bin/bash# creates a text menu for the script function diskspace {clear df-k} function whoseon {clear who} function menusage {clear cat / proc/meminfo} PS3= "Enter option:" select option in "Display diskspace"Display logged on users"\ "Display memory usage"Exit program" do case $option in "Exit program") break;; "Display diskspace") diskspace "Display logged on users") whoseon;; "Display memory usage") menusage;; *) clear echo "Wrong selection";; esacdone

The menu effect is as follows:

$menu2.sh 1) Display disk space 3) Display memory usage2) Display logged on users 4) Exit programEnter option:

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

Make window (dialog package)

The dialog package can use ANSI escape control characters to create standard window dialogs in a text environment.

Widget

The dialog package provides many widgets (widget), and the command format when used is as follows:

Dialog-widget parameters

The common components are as follows:

Msgbox widget: displays a simple message in the window with an OK button yesno widget: allows the user to select yes or no for the problem displayed in the window, and there are two buttons inputbox widget: provides a simple text box area to enter text textbox widget: can display a large amount of information in the window, will generate a scrolling window menu widget: create text menu You need to provide a selection label and display text fselect part for each option: it can be used to browse files and folders

More widgets, which are listed in detail later.

Get the output of the part

Each dialog part provides two forms of output:

Use exit status codes use STDERR

Return to option

If YES or OK is selected, the exit status code 0 is returned. If Cancel or No is selected, the exit status code 1 is returned. Can you use the standard $? Variable to determine which button is selected.

Return data

If the data is returned, the data is sent to STDERR. You can use standard bash shell methods to redirect STDERR output to another file or file descriptor:

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

For more information on how to use it, please refer to the following example.

Sample code

There is a lot of content, and I don't think it is necessary to make such a good window to exchange. Keep two things in mind when writing scripts:

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

The previous example uses the sample code implemented by the dialog package:

#! / bin/bash# create a text window menu 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] dodialog-menu "Sys Admin Menu" 20 30 10\ 1 "Display diskspace"\ 2 "Display logged on users"\ 3 "Display memory usage"\ 0 "Exit program" 2 > $temp2if [$?-eq 1] then breakfiselection=$ (cat $temp2) case $selection in0) break ; 1) diskspace;; 2) whoseon; 3) menusage;; *) dialog-msgbox "Wrong selection" 10 30esacdonerm-f $temp2 > / dev/nullrm-f $temp2 2 > / dev/null

Using temporary files here, and using the mktemp command to create temporary files, looks professional.

Install dialog package

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

[root@Ansible ~] # yum info dialog loaded plug-in: fastestmirrorLoading mirror speeds from cached hostfile * base: mirrors.aliyun.com * extras: mirrors.aliyun.com * updates: mirrors.aliyun.com installed package name: dialog Architecture: x86 * 64 version: 1.2 release: 5.20130523.el7 size: 505k Source: installed Source: base introduction: A utility for creating TTY dialog boxes URL: http : / / invisible-island.net/dialog/dialog.html: LGPLv2 description: 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 parts detail sheet

Dialog component

Part description calendar provides calendar for selecting dates checklist displays multiple options (each option can be turned on or off) form builds a form with labels and text fields (content can be filled) fselect provides a file selection window to browse the selection file gauge displays the percentage complete progress bar infobox displays a message But without waiting for a response, inputbox provides a text form for entering text inputmenu provides an editable menu menu displays a range of options msgbox displays a message and asks the user to select the OK button pause to display a progress bar to display the status during the pause passwordbox displays a text box, but hides the entered text passwordformx ranch a form with labels and hidden text fields radiolist provides a set of menu options Only one can be selected. The radio tailbox uses the tail command to display the contents of the file in the scroll window tailboxbg is more like tailbox, but running textbox in the background mode displays the contents of the file in the scroll window timebox provides a window that selects hours, minutes and seconds yesno provides a simple message dialog option with Yes and No buttons

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

Dialog command options

Option description-add-widget continues to the next dialog box Until the Esc or Cancel button is pressed-aspect ratio specifies the aspect ratio of the width to height of the window-backtitle title specifies the title displayed on the background at the top of the screen-begin x y specifies the starting position of the upper left corner of the window-clear clears the screen with the default conversation background color-colors embeds ANSI color coding in the conversation text-cr-wrap allows the use of line breaks and forces line breaks in the conversation text -- create-rc file copies the contents of the sample configuration file to the specified file file-- default-item string settings check list, The default item in a form or menu conversation-- help displays help for the dialog command-- after help-status selects the Help button Write multiple selection lists, radio lists, or form information after help information-- ignore ignores options that dialog does not recognize-- input-fd fd specifies a file descriptor other than STDIN-- insecure displays an asterisk when typing in the password part-- item-help is a multi-selection list, Each label in the radio list or menu adds a help bar at the bottom of the screen-keep-window does not clear the parts displayed on the screen-max-input size specifies the maximum string length entered. The default is 2048--no-collapse. Do not convert tabs in the conversation text into spaces-- no-kill puts the tailbox dialog box in the background And disable the SIGHUP signal of the process-- no-shadow does not display the shadow effect of the conversation window-- output-fd fd specifies an output file descriptor other than STDERR-- print-maxsize prints the maximum size of the conversation window to the output-- print-size prints the size of the conversation window to the output-- print-version prints the dialog version number to the output-- separate-output outputs the results of the checklist part one line at a time. Do not use quotation marks-separator string specifies the string used to separate the widget output-separate-widget string specifies the string used to separate the widget output-shadow draws shadows in the lower right corner of each window-single-quoted uses single quotes for the output of the multi-selection list if needed-sleep sec delays the specified number of seconds after processing the conversation window-stderr sends the output to STDERR (default behavior)-stdout Send output to STDOUT--tab-correct to convert tabs to spaces-tab-len n specifies the number of spaces occupied by a tab (default is 8)-timeout sec specifies when no user input Sec exits after seconds and returns an error code-titel title specifies the title of the conversation window-trim removes leading spaces and newline characters from the conversation text-visit-items modifies the position of tabs in the conversation window to include a list of options

Dialog Command option 2

The functions of the options of the buttons are similar, which are listed separately here. You can override any button label in the conversation window:

Option description-cancel-label label specifies an alternative label for the Cancel button-defaultno sets the default answer to the yes/no dialog box to the alternative label for the No--exit-label label specify Exit button-extra-button displays an extra button between the OK button and the Cancel button-extra-label label specifies an alternative label for the extra button-help-button displays a Help button after the OK button and the Cancel button-help-label Label specifies an alternate label for the Help button-- nocancel hides the Cancel button-- no-lable label specifies an alternate label for the No button-- ok-label label specifies an alternate label for the OK button-- yes-label label specifies an alternate label for the Yes button.

Give examples to illustrate

The title option allows you to set the widget title that appears at the top of the window. The backtitle option is an easy way to create public titles for menus in scripts. -- create-rc option, the dialog command supports run-time configuration. This command creates a profile based on the profile template. Create a local temporary file (mktemp)

When you need to temporarily save content to a file, there is a special command that can be used to create a temporary file. The mktemp command creates a unique temporary file in the / tmp directory. Shell creates this file, but does not use the default umask value. It sets the current user as the owner of the file, and only the owner has read and write access.

Create a file

By default, mktemp creates a file in the current directory. When using the command, you need to specify a file name template. The template can contain any text file name, with 6 Xs at the end of the file name (no matter how many Xs, 6 digits are recommended in the book):

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

The mktemp command replaces the six Xs with a 6-bit character code, ensuring that the file name is unique in the directory.

Use in script

When using the mktemp command in a script, you need to save the file name to a variable so that it can be referenced later in the script:

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

A few temporary files have been created here to interfere with it. When you use it, you create a file descriptor 3 to use it, and then close the file descriptor. Finally, the used temporary files were deleted accurately.

Create a temporary file in the / tmp directory

The-t option forces the mktemp command to create files in the temporary directory of the system. What is returned at this time is the full path of the created file:

$mktemp-t test3.XXXXXX/tmp/test3.aPIXIy$ create a temporary directory

The-d option is to create a temporary directory. If you want to create a temporary directory under the / tmp directory, it is-dt:

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report