如何使用Shell脚本显示对话框
时间:2020-03-05 15:31:39 来源:igfitidea点击:
本教程将提供一些示例,说明如何在Bash shell脚本中使用zenity和whiptail等实用工具来提供消息/对话框。
使用这些实用程序,脚本将能够通知用户当前的执行状态,或者提供进行交互的功能。
这两个实用程序之间的区别在于它们显示消息框或者对话框的方式。
Zenity使用GTK工具包来创建图形用户界面,而whiptail则在终端窗口内创建消息框。
Zenity工具
要在Ubuntu上安装zenity,请运行:
sudo apt-get install zenity
由于创建带有禅意性的消息框或者对话框的命令很容易说明,因此我们将为我们提供一些示例。
创建信息框
zenity --info --title "Information Box" --text "This should be information" --width=300 --height=200
创建是/否对话框
zenity --question --text "Do you want this?" --ok-label "Yeah" --cancel-label="Nope"
创建输入框并将值存储在变量中
a=$(zenity --entry --title "Entry box" --text "Please enter the value" --width=300 --height=200) echo $a
输入后,值将存储在$a变量中。
这是一个工作示例,它接受用户的名字,姓氏和年龄并显示出来。
#!/bin/bash ## This script will ask for couple of parameters # and then continue to work depending on entered values ## Giving the option to user zenity --question --text "Do you want to continue?" # Checking if user wants to proceed [ $? -eq 0 ] || exit 1 # Letting user input some values FIRSTNAME=$(zenity --entry --title "Entry box" --text "Please, enter your first name." --width=300 --height=150) LASTNAME=$(zenity --entry --title "Entry box" --text "Please, enter your last name." --width=300 --height=150) AGE=$(zenity --entry --title "Entry box" --text "Please, enter your age." --width=300 --height=150) # Displaying entered values in information box zenity --info --title "Information" --text "You are ${FIRSTNAME} ${LASTNAME} and you are ${AGE}(s) old." --width=300 --height=100
不要忘记参考一些有用的Zenity选项,这些选项可能对我们有所帮助。
Whiptail工具
在Ubuntu运行上安装Whiptail
sudo apt-get install whiptail
用于创建带有消息框的消息框/对话框的命令也很容易解释,因此我们将仅向我们提供一些基本示例。
创建消息框
whiptail --msgbox "This is a message" 10 40
创建是/否对话框
whiptail --yes-button "Yeah" --no-button "Nope" --title "Choose the answer" --yesno "Will you choose yes?" 10 30
使用默认值创建输入框
whiptail --inputbox "Enter your number please." 10 30 "10"
尝试使用输入的值时要注意的一件事是,whiptail使用stdout来显示对话框,而使用stderr来进行值输出。
这样,如果使用var = $(...),则根本不会看到对话框,也不会得到输入的值。
解决方案是切换stdout和stderr。
为此,只需在whiptail命令的末尾添加3>&1 1>&2 2>&3.
我们要使用它来获取一些输入值的任何whiptail命令都将如此。
创建菜单对话框
whiptail --menu "This is a menu. Choose an option:" 20 50 10 1 "first" 2 "second" 3 "third"
这是一个shell脚本,要求用户输入文件夹的路径,然后输出其大小。
#!/bin/bash# Since whiptail has to use stdout to display dialog, entered value will # be stored in stderr. To switch them and get the value to stdout you must # use 3>&1 1>&2 2>&3 FOLDER_PATH=$(whiptail --title "Get the size of folder" \ --inputbox "Enter folder path:" \ 10 30 \ "/home" \ 3>&1 1>&2 2>&3) if [ -d $FOLDER_PATH ] then size=$(du -hs "$FOLDER_PATH" | awk '{print }') whiptail --title "Information" \ --msgbox "Size of ${FOLDER_PATH} is ${size}" \ 10 40 elif [ -f $FOLDER_PATH ] then whiptail --title "Warning!!!" \ --msgbox "The path you entered is a path to a file not a folder!" \ 10 40 else whiptail --title "Error!!!" --msgbox "Path you entered is not recognized. Please try again" \ 10 40 fi