如何在Linux Shell脚本中添加GUI

A zenity information window launched from a Ubuntu terminal.

You can use GUI windows, sliders, radio buttons, progress bars, and more in your Bash scripts. Learn how to use the zenity toolkit and give your Bash scripts a facelift. We’ll show you how.

您可以在Bash脚本中使用GUI窗口,滑块,单选按钮,进度条等。 了解如何使用zenity工具包,并使您的Bash脚本焕然一新。 我们将向您展示如何。

Bash scripting is a powerful programming language and, because it’s built into the Bash shell, it’s readily available to everyone. It’s an easy language to start programming in. Because it’s interpreted, you don’t need to compile your scripts. As soon as you’ve edited the script file and made it executable, you can run it. This makes the coding, running, and debugging cycle quite efficient.

Bash脚本是一种功能强大的编程语言,由于它内置在Bash Shell中,因此每个人都可以使用。 这是一种易于编程的语言。由于它是经过解释的,因此您无需编译脚本。 编辑脚本文件并使其可执行后,即可运行它。 这使得编码,运行和调试周期非常有效。

There are two main complaints people have with Bash scripts, and the first is speed. Because the Bash shell interprets the commands in the script, they don’t execute as quickly as compiled code. However, this is like complaining that a tractor isn’t as fast as a car; they’re meant for different things.

人们对Bash脚本有两个主要的抱怨,第一个是速度。 由于Bash shell会解释脚本中的命令,因此它们的执行速度不如编译后的代码快。 但是,这就像在抱怨拖拉机不如汽车快。 它们意味着不同的东西。

There are two kinds of speed, though. You can often knock together a quick script and use it to perform a task much more quickly than developing a solution in a compiled language, such as C.

但是,速度有两种。 与使用C之类编译语言开发解决方案相比,您通常可以将快速脚本组合在一起并使用它来更快地执行任务。

The second complaint people have with Bash scripts is the user interface—it’s a terminal window. Of course, sometimes the interface doesn’t matter. If the only person who’ll ever use the script is its author, the interface probably isn’t that important. Nor does it matter for scripts that perform background and batch type processing. Typically, such scripts don’t need much (if any) user interaction.

人们对Bash脚本的第二个抱怨是用户界面-这是一个终端窗口。 当然,有时界面并不重要。 如果唯一会使用脚本的人是脚本作者,那么界面可能并不那么重要。 对于执行后台和批处理类型的脚本也没有关系。 通常,此类脚本不需要太多(如果有)的用户交互。

There are occasions when you do need something a little more intuitive and modern than the terminal window. Most people are familiar with a graphical user interface (GUI). To give people an experience that’s as frictionless as possible, you have to create and use GUI elements from your scripts.

在某些情况下,您确实需要比终端窗口更直观,更现代的功能。 大多数人都熟悉图形用户界面 (GUI)。 为了给人们带来尽可能流畅的体验,您必须从脚本中创建和使用GUI元素。

zenity应用 (The zenity Application)

zenity allows you to incorporate a wide range of graphical interface elements in your Bash scripts. It’s a powerful toolkit that gives your scripts a modern feel and a contemporary, familiar appearance.

zenity允许您在Bash脚本中合并各种图形界面元素。 它是一个功能强大的工具包 ,可为您的脚本带来现代感和现代感,熟悉的外观。

zenity is preinstalled on Ubuntu, Fedora and Manjaro distributions. It’s part of GNOME. If you use KDE, you might want to check out  kdialog  instead, although zenity does run on any desktop environment.

zenity已预装在Ubuntu,Fedora和Manjaro发行版中。 它是GNOME的一部分。 如果使用KDE,尽管zenity确实可以在任何桌面环境上运行,但您可能想签出kdialog

The examples in this article show you how to create the different dialog windows from the command line, how to capture their return values and user selections in variables, and how to use the dialog windows in scripts.

本文中的示例向您展示如何从命令行创建不同的对话框窗口,如何在变量中捕获它们的返回值和用户选择,以及如何在脚本中使用对话框窗口。

We finish with a small application that makes use of all three types of dialog windows.

我们以一个小型应用程序结束,该应用程序使用了所有三种类型的对话框窗口。

日历对话框窗口 (The Calendar Dialog Window)

A calendar dialog window allows someone to select a date. To create one with zenity requires a single command of two words:

日历对话框窗口允许某人选择日期。 要创建具有zenity的命令,只需一个命令,其中包含两个单词:

zenity --calendar

   
   
"zenity --calendar" in a terminal window.

The calendar dialog window appears. This has all the functionality you’d expect from a standard date-picker. You can change the month and year, and click on a day to select that date. By default, today’s date is highlighted when the window appears.

出现日历对话框窗口。 它具有您希望标准日期选择器提供的所有功能。 您可以更改月份和年份,然后单击一天以选择该日期。 默认情况下,当窗口出现时,今天的日期会突出显示。

A zenity calendar window of July 2019.

Click “OK” to close the dialog window and select the highlighted date. Double-clicking a date does the same thing.

单击“确定”关闭对话框窗口,然后选择突出显示的日期。 双击日期会做同样的事情。

If you don’t want to make a date selection, click “Cancel,” press the “Esc” key on your keyboard, or close the dialog window.

如果不想选择日期,请单击“取消”,按键盘上的“ Esc”键,或关闭对话框窗口。

A zenity calendar window with August 19, 2019 selected.

In the example above, August 19, 2019, is selected. If the user clicks “OK,” the calendar closes, and the selected date prints in the terminal window.

在上面的示例中,选择了2019年8月19日。 如果用户单击“确定”,日历将关闭,并且所选日期将显示在终端窗口中。

The date selected on the calendar (08/19/2019) shown in the terminal window.

You can ignore the line, “GTKDialog mapped without a transient parent. This is discouraged.”

您可以忽略以下行:“ GTKDialog映射,没有临时父级。” 不鼓励这样做。”

GTK stands for GIMP Tool Kit, which is the toolkit used to develop the GNOME interface. It was originally devised by the authors of the GNU Image Manipulation Program (GIMP). GNU stands for GNU’s Not Unix.

GTK代表GIMP Tool Kit ,它是用于开发GNOME界面的工具包。 它最初是由GNU图像处理程序( GIMP )的作者设计的。 GNU代表GNU的Not Unix

The GTK engine is warning the authors of zenity that they’ve used a GTK component in a nonstandard way.

GTK引擎警告zenity的作者,他们以非标准的方式使用了GTK组件。

捕获日期值 (Capturing the Date Value)

Printing the date to the terminal doesn’t do a lot for us. If we’re going to call this calendar from one of our scripts, we need to capture the selected date value so we can do something useful with it in our script. We’ll also customize the calendar slightly.

在终端上打印日期对我们没有多大帮助。 如果要从其中一个脚本中调用此日历,则需要捕获所选的日期值,以便可以在脚本中使用它进行一些有用的操作。 我们还将稍微自定义日历。

We’ll use the following options with the calendar. They must all be used with the double-dash “–” flag:

我们将在日历中使用以下选项。 它们都必须与双破折号“ –”标志一起使用:

  • –text: Specifies a string of text to display in the calendar. It replaces the default, “Select a date from below.”

    –text指定要在日历中显示的文本字符串。 它取代了默认值“从下面选择日期”。

  • –title: Sets the title of the calendar dialog window.

    –title设置日历对话框窗口的标题。

  • –day: Sets the day that’s selected when the calendar opens.

    –day设置日历打开时选择的日期。

  • –month: Sets the month that’s selected when the calendar opens.

    –month 设置日历打开时选择的月份。

  • –year: Sets the year that’s selected when the calendar opens.

    –year设置日历打开时选择的年份。

We’re using a variable called ChosenDate to capture the date returned from the calendar. And we’re using echo $ChosenDate to print that date to the terminal window.

我们正在使用一个称为ChosenDate的变量来捕获日历返回的日期。 我们正在使用echo $ChosenDate将日期打印到终端窗口。

Yes, we achieved the same result in the previous example, but here, we have the selected date stored in a variable. In the previous example, it was printed and forgotten.

是的,我们在上一个示例中获得了相同的结果,但是在这里,我们将所选日期存储在变量中。 在前面的示例中,它已被打印并遗忘了。

ChosenDate=$(zenity -- calendar --text "Choose a date" --title "How-To Geek Rota" --day 1 -- month 9 --year 2019); echo $ChosenDate
"ChosenDate=$(zenity -- calendar --text "Choose a date" --title "How-To Geek Rota" --day 1 -- month 9 --year 2019); echo $ChosenDate" in a terminal window.

Now, the calendar displays our prompt and our window title. The date is set to our chosen start date rather than today’s date.

现在,日历显示我们的提示和窗口标题。 该日期设置为我们选择的开始日期,而不是今天的日期。

zenity calendar with a start date selected (September 1, 2019).

We can also customize the format of the date string returned when a selection is made. The --date-format option must be followed by a format specifier. This is a string of tokens that define the data and formats that are to be included in the output. The tokens are the same as those used with the strftime() C language function and there’s a huge selection of them.

我们还可以自定义选择后返回的日期字符串的格式。 --date-format选项之后必须是格式说明符。 这是一串标记,用于定义要包含在输出中的数据和格式。 令牌与strftime() C语言函数使用的令牌相同,并且有很多选择。

The tokens we’re using are:

我们使用的令牌是:

  • %A: The full name of the day of the week.

    %A星期几的全名。

  • %d: The day of the month as a digit.

    %d数字中的月份。

  • %m: The month as a digit.

    %m月份,以数字表示。

  • %y: The year as two digits (no century).

    %y以两位数字表示的年份(无世纪)。

ChosenDate=$(zenity -- calendar --text "Choose a date" --title "How-To Geek Rota" --date-format="%A %d/%m/%y" --day 1 -- month 9 --year 2019); echo $ChosenDate
"ChosenDate=$(zenity -- calendar --text "Choose a date" --title "How-To Geek Rota" --date-format="%A %d/%m/%y" --day 1 -- month 9 --year 2019); echo $ChosenDate" in a terminal window.

Someone selects a date:

有人选择一个日期:

zenity calendar window with September 16, 2019 selected.

And the date is returned using our format. It shows the name of the day of the week, followed by the date in European order: day, month, year.

并使用我们的格式返回日期。 它显示星期几的名称,然后按照欧洲顺序显示日期:日,月,年。

European formatted date returned by a calendar in a terminal window.

“文件选择”对话框窗口:选择文件 (The File Selection Dialog Window: Choosing a File)

File selection dialog windows are quite complex. People can browse through the file system, highlight a file or files, and then click “OK” to select those files or cancel the selection altogether.

文件选择对话框窗口非常复杂。 人们可以浏览文件系统,突出显示一个或多个文件,然后单击“确定”以选择那些文件或完全取消选择。

zenity provides all this functionality, and more. And it’s just as easy to use as the calendar dialog window.

zenity提供了所有这些功能,以及更多。 它和日历对话框窗口一样容易使用。

The new options we’re going to use are:

我们将使用的新选项是:

  • –file-selection: Tells zenity we want to use a file selection dialog window.

    –file-selection告诉zenity我们要使用文件选择对话框窗口。

  • –multiple: Allows someone to select more than one file.

    –multiple允许某人选择多个文件。

  • –file-filter: Tells the file dialog window which file types to display.

    –file-filter告诉文件对话框窗口要显示的文件类型。

zenity --file-selection --tile "How-To Geek" --multiple --file-filter='*.mm *.png *.page *.sh *.txt'
"zenity --file-selection --tile "How-To Geek" --multiple --file-filter='*.mm *.png *.page *.sh *.txt' " in a terminal window.

The file selection dialog window is as functional as any other file selection window.

文件选择对话框窗口与任何其他文件选择窗口一样功能。

zenity file section dialog window with a folder selected.

The user can browse through the file system and select the file of her choice.

用户可以浏览文件系统并选择自己选择的文件。

zenity file selection dialog window with a file selected

We’ve browsed to a new directory and selected a file called “button_hybrid.png.”

我们已经浏览到一个新目录,并选择了一个名为“ button_hybrid.png”的文件。

When you click “OK,” the file selection dialog window closes, and the filename and path print in the terminal window.

当您单击“确定”时,文件选择对话框窗口关闭,文件名和路径在终端窗口中打印。

The selected file name in a terminal window.

If you need to use the filename in any further processing, you can capture it in a variable, just as you did for the date from the calendar.

如果需要在进一步处理中使用文件名,则可以将其捕获到变量中,就像处理日历中的日期一样。

“文件选择”对话框窗口:保存文件 (The File Selection Dialog Window: Saving a File)

If we add one option, we can turn the file selection dialog window into a file save dialog window. The option is --save. We’re also going to use the  --confirm-overwrite option. This prompts the person to confirm he wants to overwrite an existing file.

如果添加一个选项,则可以将文件选择对话框窗口变成文件保存对话框窗口。 选项是--save 。 我们还将使用--confirm-overwrite选项。 这会提示该人确认他要覆盖现有文件。

Response=$(zenity --file-selection --save --confirm-overwrite); echo $Response
"Response=$(zenity --file-selection --save --confirm-overwrite); echo $Response" in a terminal window.

The file save dialog window appears. Note there’s a text field where someone can type a filename.

出现文件保存对话框窗口。 请注意,在一个文本字段中,有人可以键入文件名。

zenity file save dialog window.

The user can browse to the location of his choice within the file system, provide a name for the file, or click an existing file to overwrite it.

用户可以浏览到文件系统中自己选择的位置,为文件提供名称,或单击现有文件以覆盖它。

zenity file save dialog with an existing file selected.

In the example above, the user highlighted an existing file.

在上面的示例中,用户突出显示了一个现有文件。

When he clicks “OK,” a confirmation dialog window appears asking him to confirm he wants to replace the existing file. Note the name of the file appears in the warning dialog. That’s the sort of attention to detail that gives zenity its professional appearance.

当他单击“确定”时,将出现一个确认对话框,要求他确认要替换现有文件。 注意,文件名出现在警告对话框中。 那种对细节的关注使zenity具有专业外观。

If we hadn’t used the --confirm-overwrite option, the file would have been silently overwritten.

如果我们没有使用--confirm-overwrite选项,则该文件将被静默覆盖。

zenity overwrite confirmation dialog.

The name of the file is stored in the variable Response, which prints to the terminal window.

文件名存储在变量Response ,该变量显示在终端窗口中。

A saved file name in a terminal window.

通知对话框窗口 (Notification Dialog Windows)

With zenity, including slick notification dialog windows in your scripts is effortless. There are stock dialog windows you can call upon to provide information, warnings, error messages, and questions for the user.

使用zenity ,可以轻松地在脚本中包含通知对话框。 您可以调用一些库存对话框窗口来为用户提供信息,警告,错误消息和问题。

To create an error message dialog window, use the following command:

要创建错误消息对话框窗口,请使用以下命令:

zenity --error --width 300 --text "Permission denied. Cannot write to the file."

The new options we’re using are:

我们正在使用的新选项是:

  • –error: Tells zenity we want to use an error dialog window.

    -错误告诉zenity我们想用一个错误对话框。

  • –width: Sets the initial width of the window.

    –width设置窗口的初始宽度。

"zenity --error --width 300 --text "Permission denied. Cannot write to the file." in a terminal window.

The error dialog window appears at the specified width. It uses the standard GTK error icon.

错误对话框窗口以指定的宽度出现。 它使用标准的GTK错误图标。

zenity error dialog window.

To create an information dialog window, use the following command:

要创建信息对话框窗口,请使用以下命令:

zenity --info --width 300 --text "Update complete. Click OK to continue."

The new option we’re using is --info , which tells zenity to create an information dialog window.

我们使用的新选项是--info ,它告诉zenity创建一个信息对话框窗口。

zenity information dialog window.

To create a question dialog window, use the following command:

要创建问题对话框窗口,请使用以下命令:

zenity --question --width 300 --text "Are you happy to proceed?"; echo $?

The new option we’re using is --question, which tells zenity to create a question dialog window.

我们正在使用的新选项是--question ,它告诉zenity创建一个问题对话框窗口。

"zenity --question --width 300 --text "Are you happy to proceed?"; echo $?" in a terminal window.

The $? is a special parameter. It holds the return value from the most recently executed foreground pipeline. In general terms, this is the value from the most recently closed process. A zero value means “OK,” and a value of one or more means “Cancel.”

$? 是一个特殊参数 。 它保存了最近执行的前台管道的返回值。 一般而言,这是最近关闭过程的价值。 零值表示“确定”,而一个或多个值表示“取消”。

This is a general technique you can apply to any of the zenity dialog windows. By checking this value in your script, you can determine whether the data returned from a dialog window should be processed or ignored.

这是一种通用技术,可以应用于任何zenity对话框窗口。 通过检查脚本中的该值,可以确定是否应处理或忽略从对话框窗口返回的数据。

zenity question dialog.

We clicked “Yes,” so the return code is a zero indicating “OK.”

我们单击“是”,因此返回码为零,表示“确定”。

Zero (0) return code in a terminal window.

To create a warning dialog window, use the following command:

要创建警告对话框窗口,请使用以下命令:

zenity --warning --title "Low Hard Drive Space" --width 300 --text "There may not be enough hard drive space to save the backup."

The new option we’re using is --warning , which tells zenity to create a warning dialog window.

我们使用的新选项是--warning ,它告诉zenity创建一个警告对话框窗口。

"zenity --warning --title "Low Hard Drive Space" --width 300 --text "There may not be enough hard drive space to save the backup." in a terminal window.

The warning dialog window appears. It’s not a question, so it only has one button.

出现警告对话框。 这不是一个问题,因此只有一个按钮。

zenity warning dialog window.

进度对话框窗口 (The Progress Dialog Window)

You can use the zenity progress dialog window to display a progress bar that indicates how close to completion your script is.

您可以使用zenity进度对话框窗口显示进度条,该进度条指示脚本的完成程度。

The progress bar is advanced according to the values that get piped into it from your script. To demonstrate the principle, use the following command:

根据从脚本传递到进度条的值来推进进度条。 为了说明该原理,请使用以下命令:

(for i in $(seq 0 10 100); do echo $i; sleep 1; done)
"(for i in $(seq 0 10 100); do echo $i; sleep ; done)" in a terminal window.

The command breaks down like this:

该命令分解如下:

  • The seq command steps through a sequence from 0 to 100, in steps of 10.

    seq命令以从10到10的顺序逐步执行从0到100的序列。

  • At each step, the value is stored in the variable i. This prints to the terminal window.

    在每个步骤中,该值都存储在变量i 。 这将打印到终端窗口。

  • The command pauses for one second, due to the sleep 1 command.

    由于sleep 1命令,该命令暂停一秒钟。

We can use this with the zenity progress dialog window to demonstrate the progress bar. Note we’re piping the output of the previous command into zenity:

我们可以在zenity进度对话框窗口中使用它来演示进度条。 注意,我们将前一个命令的输出zenity:zenity:

(for i in $(seq 0 10 100); do echo $i; sleep 1; done) | zenity --progress --title "How-To Geek" -- auto-close
"(for i in $(seq 0 10 100); do echo $i; sleep 1; done) | zenity --progress --title "How-To Geek" -- auto-close" in a terminal window.

The new options we’re using are:

我们正在使用的新选项是:

  • –progress: Tells zenity we want to use a progress dialog window.

    -progress:告诉zenity我们想用一个进度对话框窗口。

  • –auto-close: Closes the dialog when the progress bar reaches 100 percent.

    –auto-close进度条达到100%时,关闭对话框。

The progress dialog window appears, and the bar advances towards 100 percent, pausing for one second between each step.

出现进度对话框窗口,并且进度条向100%前进,在每个步骤之间暂停一秒钟。

zenity progress dialog.

We can use that concept of piping values into zenity to include the progress dialog window in a script.

我们可以使用将值zenityzenity概念来将进度对话框窗口包括在脚本中。

Enter this text in an editor and save it as “progress.sh.”

在编辑器中输入此文本,并将其另存为“ progress.sh”。

!/bin/bash

function work-list () {

echo "# First work item" 
echo "25"
sleep 1

echo "# Second work item" 
echo "50"
sleep 1

echo "# Third work item" 
echo "75"
sleep 1

echo "# Last work item" 
echo "100"
sleep 1

}

work-list | zenity --progress --title "How-To Geek" --auto-close

exit 0

Here’s a breakdown of the script:

这是脚本的细分:

  • The script defines a function called work-list. This is where you put your commands and instructions to perform real work. Replace each of the sleep 1 commands with your real ones.

    该脚本定义了一个名为work-list的函数。 在这里放置命令和说明以执行实际工作。 用您的真实命令替换每个sleep 1命令。

  • zenity accepts the echo "# ..." lines and displays them within the progress dialog window. Change the text of these lines, so they pass informative messages to the user.

    zenity接受echo "# ..."行并将其显示在进度对话框窗口中。 更改这些行的文本,以便它们将信息传递给用户。

  • The echo lines that contain numbers, such as echo "25" , are also accepted by zenity and set the value of the progress bar.

    包含数字的echo线(例如echo "25" )也会被zenity接受并设置进度条的值。

  • The work-list function is called and piped into zenity.

    工作清单函数被调用并通过管道zenityzenity

Use this command to make the script executable:

使用此命令使脚本可执行:

chmod +x progress.sh
"chmod +x progress.sh" in a terminal window.

Use this command to run the script:

使用此命令运行脚本:

./progress.sh
"./progress.sh" in a terminal window.

The script runs, and the text message changes as each phase of the script executes. The progress bar moves in steps toward 100 percent.

脚本将运行,并且文本消息会在脚本的每个阶段执行时发生变化。 进度条将逐步向100%移动。

zenity progress bar dialog window.

比例对话框窗口 (The Scale Dialog Window)

The scale dialog window lets someone move a slider to choose a numeric value. This means she can’t input a value that’s too high or low.

比例对话框窗口允许某人移动滑块以选择数字值。 这意味着她不能输入太高或太低的值。

The new options we’re using are:

我们正在使用的新选项是:

  • –scale: Tells zenity we want to use a scale dialog window.

    进制告诉zenity我们想用一个尺度对话窗口。

  • –min-value: Sets the minimum value for the scale.

    –min-value设置刻度的最小值。

  • –max-value: Sets the maximum value for the scale.

    –max-value设置刻度的最大值。

  • –step: Sets the amount the slider moves in when the arrow keys are used. This doesn’t affect slider movements if someone uses the mouse.

    –step设置使用箭头键时滑块移动的量。 如果有人使用鼠标,这不会影响滑块的移动。

  • –value: Sets the initial value and position of the slider.

    –value设置滑块的初始值和位置。

This is the command we’re using:

这是我们正在使用的命令:

Response=$(zenity --scale --title "How-To Geek" --text "Select magnification." --min-value=0 --max-value=30 --step=3 --value15); echo $Response
"Response=$(zenity --scale --title "How-To Geek" --text "Select magnifcation." --min-value=0 --max-value=30 --step=3 --value15); echo $Response" in a terminal window.

The slider dialog window appears with the slider set to 15.

出现滑块对话框窗口,并将滑块设置为15。

zenity scale dialog window.

The user can move the slider to select a new value.

用户可以移动滑块以选择新值。

zenity scale dialog with user selection

When she clicks “OK,” the value is transferred to the variable Response and printed to the terminal window.

当她单击“确定”时,该值将传输到变量Response并打印到终端窗口。

zenity scale value in a terminal window.

输入对话框窗口 (The Entry Dialog Window)

The entry dialog window allows someone to input text.

输入对话框窗口允许某人输入文本。

The new options we’re using are:

我们正在使用的新选项是:

  • –entry: Tells zenity we want to use an entry dialog window.

    –entry告诉zenity我们要使用输入对话框窗口。

  • –entry-text: You can use this if you want to type a suggested value in the text input field. We’re using “” to force an empty field. This isn’t strictly required, but we wanted to document the option.

    –entry-text如果要在文本输入字段中输入建议值,可以使用此选项。 我们使用“”强制为空字段。 这不是严格要求,但我们想记录该选项。

The full command looks like this:

完整的命令如下所示:

Response=$(zenity --entry --text "Enter your search term" --title "Howe-To Geek" --entry-text=""); echo $Response
"Response=$(zenity --entry --text "Enter your search term" --title "Howe-To Geek2 --entry-text=""); echo $Response" in a terminal window.

A simple dialog window appears, containing a text entry field.

出现一个简单的对话框窗口,其中包含一个文本输入字段。

zenity entry dialog window.

Someone can type and edit text.

有人可以键入和编辑文本。

zenity entry dialog window with typed text in the text field.

When he clicks “OK,” the value he typed is assigned to the variable Response. We use echo to print the value of the variable in the terminal window.

当他单击“确定”时,他键入的值将分配给变量Response。 我们使用echo在终端窗口中打印变量的值。

User text entry term in a terminal window.

放在一起 (Putting It All Together)

Let’s put these techniques together and create a functional script. The script will perform a hardware info scan and present the results to the user in a scrolling text window. She can choose a long or short scan type.

让我们将这些技术放在一起,创建一个功能脚本。 该脚本将执行硬件信息扫描,并在滚动文本窗口中将结果呈现给用户。 她可以选择长扫描或短扫描类型。

For this script, we’ll use three types of dialog windows, two of which are new to us:

对于此脚本,我们将使用三种类型的对话框窗口,其中两种对我们来说是新的:

  • The first is a list dialog window. It allows someone to make a choice.

    第一个是列表对话框窗口。 它允许某人做出选择。
  • The second is a progress dialog window that lets the user know something is happening, and she should wait.

    第二个是进度对话框窗口,让用户知道正在发生的事情,她应该等待。
  • The third is a text information window, which displays the results to the user.

    第三个是文本信息窗口,该窗口将结果显示给用户。

Enter this text in an editor and save it as “hardware-info.sh.”

在编辑器中输入此文本,并将其另存为“ hardware-info.sh”。

#!/bin/bash

# Display hardware listing for this computer

TempFile=$(mktemp)

ListType=`zenity --width=400 --height=275 --list --radiolist \
     --title 'Hardware Scan' \
     --text 'Select the scan type:' \
     --column 'Select' \
     --column 'Scan Type' TRUE "Short" FALSE "Long"`

if [[ $? -eq 1 ]]; then

  # they pressed Cancel or closed the dialog window 
  zenity --error --title="Scan Declined" --width=200 \
       --text="Hardware scan skipped"
  exit 1
 
elif [ $ListType == "Short" ]; then

  # they selected the short radio button 
  Flag="--short"
 
else

  # they selected the long radio button 
  Flag="" 
fi

# search for hardware info with the appropriate value in $Flag
hwinfo $Flag | tee >(zenity --width=200 --height=100 \
     --title="Collating Information" --progress \
     --pulsate --text="Checking hardware..." \
     --auto-kill --auto-close) >${TempFile}
 
# Display the hardware info in a scrolling window
zenity --width=800 --height=600 \
     --title "Hardware Details" \
     --text-info --filename="${TempFile}"
 
exit 0

Use this command to make it executable:

使用此命令使其可执行:

chmod +x hardware-info.sh
"chmod +x haredware-info.sh in a" terminal window.

This script creates a temporary file, and the name of the file is held in the TempFile variable:

此脚本创建一个临时文件,文件名保存在TempFile变量中:

TempFile=$(mktemp)

The script uses the --list option to create a zenity dialog window called a list dialog window. The “\” characters at the end of the lines tell the script to treat them as one long line that’s wrapped around. Here’s the process:

该脚本使用--list选项创建一个称为列表对话框窗口的zenity对话框窗口。 行尾的“ \”字符告诉脚本将其视为一条环绕的长行。 流程如下:

  • We specify a width and height for the window.

    我们为窗口指定宽度和高度。
  • The list dialog window supports columns. The --radiolist option causes the first column to be a column of radio buttons.

    列表对话框窗口支持列。 --radiolist选项使第一列成为单选按钮的列。

  • We set a title and text prompt for the window.

    我们为窗口设置标题和文本提示。
  • We set the title of the first column to be “Select.” The content of this column will be the radio buttons.

    我们将第一列的标题设置为“选择”。 此列的内容将是单选按钮。
  • We set the title of the second column to be “Select,” and we provide the content of the second column. This column holds two text labels: “Short” and “Long.” The TRUE and FALSE indicators mean the “Short” option is selected by default when the dialog window appears.

    我们将第二列的标题设置为“选择”,并提供第二列的内容。 该列包含两个文本标签:“短”和“长”。 TRUE和FALSE指示符表示对话框窗口出现时默认选择“ Short”选项。
  • We’re storing the result from this dialog window in a variable called ListType.

    我们ListType对话框窗口的结果存储在名为ListType的变量中。

ListType=`zenity --width=400 --height=275 --list --radiolist \ 
     --title 'Hardware Scan' \ 
     --text 'Select the scan type:' \ 
     --column 'Select' \ 
     --column 'Scan Type' TRUE "Short" FALSE "Long"`

If the user presses “Cancel,” we don’t need to check the value in ListType, we can simply exit. If he presses “OK,” we need to find out if he selected the “Short” or “Long” radio button:

如果用户按下“取消”,则无需检查ListType,的值,只需退出即可。 如果他按下“确定”,我们需要找出他是否选择了“短”或“长”单选按钮:

  • The special parameter $? equals zero if the user pressed “OK.” It equals one if he pressed “Cancel” or closed the window.

    特殊参数$? 如果用户按下“确定”,则等于零。 如果他按“取消”或关闭窗口,则等于1。

  • If it equals one, the script displays an error information dialog window and exits. If he presses “OK,” we move on to test the value in the ListType variable.

    如果等于1,则脚本将显示错误信息对话框窗口并退出。 如果他按下“ OK”,我们继续测试ListType变量中的值。

  • If the ListType variable holds the value “Short,” the script sets a variable called Flag to equal “–short.”

    如果ListType变量的值是“ Short”,则脚本ListType名为Flag的变量设置为等于“ -short”。

  • If the ListType variable doesn’t hold the value “Short,” it must hold the value “Long.” The script sets a variable called Flag to equal “”, which is an empty string.

    如果ListType变量不包含“ Short”值,则它必须包含“ Long”值。 脚本将名为Flag的变量设置为等于“”,这是一个空字符串。

  • The script uses the Flag variable in the next section.

    该脚本在下一部分中使用Flag变量。

if [[ $? -eq 1 ]]; then 

  # they pressed Cancel or closed the dialog window 
  zenity --error --title="Scan Declined" --width=200 \ --text="Hardware scan skipped" 
  exit 1 

elif [ $ListType == "Short" ]; then 

 # they selected the short radio button 
 Flag="--short" 

else 

 # they selected the long radio button 
 Flag="" 
fi

Now that the script knows which type of scan the user wants, we can perform the hardware information scan:

既然脚本知道了用户想要的扫描类型,我们就可以执行硬件信息扫描:

  • The script calls the hwinfo command and passes it the value in the Flag variable.

    该脚本调用hwinfo命令,并将其值传递给Flag变量。

  • If Flag contains “–short,” the hwinfo command performs a short scan. If the value of Flag is “”, nothing passes to hwinfo and a default, long scan is performed.

    如果Flag包含“ -short”,则hwinfo命令执行短扫描。 如果Flag值为“”,则没有任何信息传递给hwinfo并且执行默认的长时间扫描。

  • The script pipes the output from hwinfo into tee. tee sends the output into zenity and the TempFile.

    该脚本将hwinfo的输出通过管道hwinfoteetee将输出发送到zenity TempFile

  • The script creates a progress bar dialog window. It sets the width and the height of the dialog window, and the title and prompt texts.

    该脚本将创建一个进度条对话框窗口。 它设置对话框窗口的宽度和高度,以及标题和提示文本。
  • The script cannot know in advance how much information the hwinfo command will produce, so it cannot set the progress bar to advance correctly to 100 percent. The --pulsate option causes the progress dialog to display a moving indicator. This informs the user something is happening and he should wait.

    该脚本无法预先知道hwinfo命令将产生多少信息,因此无法将进度条设置为正确地前进到100%。 --pulsate选项使进度对话框显示移动指示器。 这通知用户发生了什么事,他应该等待。

  • The --auto-kill option terminates the script if someone clicks “Cancel.”

    如果有人单击“取消”,则--auto-kill选项将终止脚本。

  • The --auto-close option causes the progress dialog to close automatically when the process it’s monitoring completes.

    --auto-close选项使进度对话框在其监视的进程完成时自动关闭。

# search for hardware info with the appropriate value in $Flag
hwinfo $Flag | tee >(zenity --width=200 --height=100 \
     --title="Collating Information" --progress \
     --pulsate --text="Checking hardware..." \
     --auto-kill --auto-close) >${TempFile}

When the hwinfo scan completes, the script calls zenity to create a text information dialog window with the --text-info option. The text information dialog window displays the contents of the TempFile file:

hwinfo扫描完成时,脚本将调用zenity来创建带有--text-info选项的文本信息对话框窗口。 文本信息对话框窗口显示TempFile文件的内容:

  • The script sets the width and height of the dialog window and the title text.

    该脚本设置对话框窗口的宽度和高度以及标题文本。
  • The --flename option is used to read the contents of the file held in the TempFIle variable.

    --flename选项用于读取保存在TempFIle变量中的文件的内容。

# Display the hardware info in a scrolling window 
zenity --width=800 --height=600 \ 
     --title "Hardware Details" \ 
     --text-info --filename="${TempFile}"

When the user closes the text information dialog window, the script exits.

当用户关闭文本信息对话框窗口时,脚本退出。

exit 0

Let’s fire it up and take a look.

让我们来看看。

./hardware-info.sh
"./hardware-info.sh" in a terminal window.

The list box appears. The “Short” option is selected by default.

出现列表框。 默认情况下,“短”选项被选中。

List dialog box with the "Short" option selected.

Let’s select “Long,” and then click “OK.”

我们选择“长”,然后单击“确定”。

List dialog box with the "Long" option selected.

The progress window appears with a sliding indicator. It remains on the screen until the hardware scan is completed.

将显示进度窗口,并带有一个滑动指示器。 它会保留在屏幕上,直到完成硬件扫描为止。

Progress window with a sliding indicator.

When the hardware scan is complete, the text information dialog window appears with details from the scan.

硬件扫描完成后,将显示文本信息对话框窗口,其中包含扫描的详细信息。

Hardware scan information in a text info dialog window.

Click “OK.”

点击“确定”。

Even a die-hard command-line jockey has to admit a couple of GUI dialog windows can give a humble Bash script a professional touch.

即使是顽固的命令行骑师也必须承认几个GUI对话窗口也可以使不起眼的Bash脚本具有专业水准。

翻译自: https://www.howtogeek.com/435020/how-to-add-a-gui-to-linux-shell-scripts/

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值