قالب وردپرس درنا توس
Home / Tips and Tricks / How to Add a GUI to Linux Shell Scripts

How to Add a GUI to Linux Shell Scripts



  A zenity information window launched from an 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 to give your bash scripts a new look. We show you how it works.

Bash scripts are a powerful programming language. Because they are integrated into the bash shell, they are available to everyone. It is a simple programming language. Because it's interpreted, you do not need to compile your scripts. Once you've edited the script file and made it executable, you can run it. This makes the programming, execution and debugging cycle very efficient.

There are two main complaints with bash scripts, and the first one is speed. Because the bash shell interprets the commands in the script, they are not executed as fast as compiled code. However, this is like complaining that a tractor is not as fast as a car. They are intended for different purposes.

However, there are two types of speed. Often you can put together a quick script and do a task much faster than developing a solution in a compiled language like C.

The second complaint with bash scripts is the UI ̵

1; it's a terminal window. Of course, sometimes the interface does not matter. If the only person using the script is the author, the interface is probably not that important. It also does not matter for scripts that perform background and batch type processing. Typically, such scripts do not require much (if any) user interaction.

In some cases, something is more intuitive and modern than the terminal window. Most people are familiar with a graphical user interface (GUI). To give people the smoothest possible user experience, you need to create and use GUI elements from your scripts.

The Zenity application

Zenity lets you integrate a variety of graphical interface elements into your Bash scripts. It's a powerful toolkit that gives your scripts a modern look.

Zenity is preinstalled on Ubuntu, Fedora, and Manjaro distributions. It is part of GNOME. If you are using KDE, you can check out kdialog instead, even though zenity runs in any desktop environment.

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

We conclude with a small application that uses all three types of dialog boxes. [19659013] The Calendar Dialog

In a calendar dialog, a person can select a date. To create one with zenity just type in a command with two words:

  zenity --calendar 

The Calendar dialog box appears. This provides all the functions you expect from a standard date picker. You can change the month and year and click on a day to select this date. By default, today's date is highlighted when the window is displayed.

 A zenity calendar window from July 2019.

Click "OK" to close the dialog box and select the highlighted date. Double clicking on a date does the same.

If you do not want to make a date selection, click "Cancel", press the "Esc" key on your keyboard or close the dialog box.

 A Zenity calendar window selected August 19, 2019.

In the above example, August 19, 2019 was selected. When the user clicks "OK", the calendar is closed and the selected date is printed in the terminal window.

 The date selected in the calendar (19.08.2013) is displayed in the terminal window.

You can ignore the "GTKDialog without transient parent assigned" line. This is not recommended. "

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

The GTK engine warns the authors of zenity that they have used a GTK component in a non-standard way.

Capturing the date value

Printing the Date to the terminal does not bring us much. When we call this calendar from one of our scripts, we need to capture the selected date value so that we can make something useful in our script. The calendar is also adjusted slightly.

The following options are used for the calendar. They must all be used with the double dash "-":

  • -text : Specifies a text string to be displayed in the calendar. Replaces the default setting "Select date from below".
  • -title : Sets the title of the calendar dialog box.
  • -day : Sets the day that is selected when opening the calendar.
  • Month : Sets the month selected when the calendar is opened.
  • -year : Sets the year selected when opening the calendar.

We use a variable named ChosenDate to capture the date returned by the calendar. And we use echo $ ChosenDate to print this date in the terminal window.

Yes, we did the same thing in the previous example, but here we saved the selected date in a variable. In the previous example, it was printed and forgotten.

  ChosenDate = $ (Zenity - Calendar - Select Date - Title "How-To Geek Rota" - Day 1 - Month 9 - Year 2019); echo $ ChosenDate 

The calendar now displays our prompt and our window title. The date will be set to the start date we have chosen and not to today's date.

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

You can also customize the format of the date string Returned when a selection is made. The option - date format must be followed by a format identifier. This is a string that defines the data and formats to include in the output. The tokens are the same as those used with the language function strftime () C, and there is a wide range of them.

The tokens we use are:

  • % A : The full name of the day of the week.
  • % d : The day of the month as a digit.
  • % m : The month as a numeral.
  • % y : The year as two digits (no century).
  ChosenDate = $ (Zenity - Calendar - Select Date - Title How-To Geek Rota - Date Format = "% A% d /% m /% y" - Day 1 - Month 9 - Year 2019) ; echo $ ChosenDate 

Someone selects a date:

 Zenity calendar window with selection from September 16, 2019.

And the date is returned in 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 from a calendar in a terminal window.

File Selection Dialog Box: Selecting a File

File selection dialog boxes are quite complex. Users can browse the file system, select one or more files, and then click OK to select these files or deselect them altogether.

Zenity offers all these features and more. And it's just as easy to use as the calendar dialog box.

The new options we will use are:

  • – File Selection : Says Zenity We would like to use a file selection dialog box.
  • -more : Allows you to select multiple files.
  • -File Filter : Specifies the file selection dialog box, the file types to display.
  zenity --file-selection --tile "how-to geek" --multiple --file-filter = & # 39; *. mm * .png * .page * .sh * .txt & # 39; [19659084]  

The File Selection dialog is just as functional as any other file selection window.

 Zenity file space dialog box with a selected folder.

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

 Zenity file selection dialog box with a selected file

We searched a new directory and chose a file named "button_hy" brid.png. "

If you click" OK ", the file selection dialog will close and the file name and path will be printed in the terminal window.

 The selected file name in a terminal window.

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

The File Selection Dialog Box: Saving a File

When we add an option, we can turn the File Selection dialog box into a file save dialog box. The option is - Save . We will also use the option - Confirm Overwrite . This prompts the person to confirm that they want to overwrite an existing file.

  Response = $ (zenity --file-selection --save --confirm-overwrite); echo $ Response 

The save file dialog appears. Note that there is a text box where someone can enter a filename.

 Dialog box for saving zenity files.

The user can navigate to the location of their choice in the file system and enter a name for the file file, or click on an existing file to overwrite it.

 Dialog box for saving the Zenity file with a selected existing file.

In the above example, the user has marked an existing file.

When he Clicks OK, a confirmation dialog box appears asking you to confirm that you want to replace the existing file. Note that the name of the file appears in the warning dialog box. This attention to detail gives Zenity its professional appearance.

If we had not used the option - Confirm Overwrite the file would have been overwritten unnoticed.

 Confirmation dialog for overriding Zenity.

The name of the file is stored in the variable Response which is printed in the terminal window.

 A Name of the saved file in a terminal window.

Notification dialog box

With zenity you can easily insert notification dialog boxes into your scripts. There are warehouse dialog boxes where you can provide information, alerts, error messages, and questions to the user.

Use the following command to create an error message dialog box:

  zenity --error --width 300 --text "Permission denied. Can not write to file." 

The new options we use are:

  • -error : Says Zenity what we want Use an error dialog box.
  • -width : Sets the original width of the window.

The error dialog box appears in the specified width. The default GTK error symbol is used.

 Zenity error dialog box.

Use the following command to create an information dialog box:

  zenity --info --width 300 - Text "Update complete, click OK to continue." 

The new option we are using is - info which instructs Zenity to create an information dialog box. [19659003]   Zenity information dialog box.

Use the following command to create a question dialog box:

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

The new option we are using is - question specifying zenity to create a question dialog box.

$? is a special parameter. It contains the return value of the last foreground pipeline executed. In general, this is the value from the last completed process. A null value means "OK" and a value of at least one "Cancel".

This is a general technique that you can apply to any of the Zenity dialog boxes. By checking this value in your script, you can determine whether to process or ignore the data returned by a dialog box.

 Dialogue for Zenity Questions.

We clicked on "Yes", so on "Back" code is a zero indicating "OK".

 Zero (0) return code in a terminal window.

Use the following command to create a warning dialog box:

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

The new option we are using is - warning instructing zenity to create a warning dialog box.

The warning dialog box appears. It's not a question, there is only one button.

 Dialog Box

The Progress Dialog

You can use the Zenity Progress dialog box to display a progress bar indicating how close your script is to completion ,

The progress bar expands according to the values ​​passed to it by your script. Use the following command to illustrate the principle:

  (for i in $ (seq 0 10 100), echo $ i, sleep 1, do) 

The command aborts as follows:

  • The command seq cycles through a sequence from 0 to 100 in increments of 10.
  • At each step, the value is stored in the variable i , This is printed in the terminal window.
  • The command is suspended for one second due to the command sleep 1 .

We can use this with the progress dialog box zenity to demonstrate the progress bar. Note that we direct the output of the previous command in zenity:

  (for i in $ (seq 0 10 100); echo $ i; sleep 1; done) | zenity --progress --title "How-To Geek" - Auto close 

The new options we use are:

  • -progress : Tells Zenity We want to use a progress dialog box.
  • - Auto Close : Closes the dialog when the progress bar reaches 100 percent.

The progress dialog box is displayed The bar moves to 100 percent and pauses for a second between steps.

 Zenity Progress Dialog.

We can use this concept of passing values ​​in Zenity to include the values ​​progress dialog box in a script.

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

! / bin / bash

working worklist () {

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

}

Worklist | zenity --progress --title "How - To Geek" --auto - close

exit 0 

Here is a breakdown of the script:

  • The script defines a function named work-list . Here you use your orders and instructions to do real work. Replace each of the sleep 1 commands with your real ones.
  • zenity accepts the echo "# ..." lines and displays them within the progress of dialog windows. Modify the text of these lines to forward informative messages to the user.
  • The Echo Lines contain the numbers such as Echo "25" are also used by zenity and set the value of the progress bar.
  • The worklist function is called and redirected to zenity .

Use this command to make the script executable: [19659015] chmod + x progress.sh

Use this command to execute the script:

  ./ progress. sh 

The script is executed and the text message is changed as each phase of the script is executed. The progress bar moves gradually toward 100 percent.

 Dialog Box

The Scale Dialog Box

The Scale dialog allows you to move a slider to select a numeric value. This means that it can not enter too high or too low a value.

The new options we use are:

  • -scale : Says Zenity What we want Use a scale dialog box.
  • -min-value : Sets the minimum value for the scale.
  • -max value : Sets the maximum value for the scale.
  • -step : Sets the amount by which the slider moves when the arrow keys are used. This does not affect the movements of the slider when someone uses the mouse.
  • -value : Sets the initial value and position of the slider.

This is the command we use:

  Response = $ (zenity --scale --title "how-to geek" --text "select magnification." --Min-value = 0 --max -value = 30 - step = 3 - value 15); echo $ Response 

The Slider dialog box is displayed with the slider at 15 new value.

 Zenit Scale dialog with user selection

When you click "OK", the value is transferred to the variable response and to the terminal window [19659003]   zenith value in a terminal window ,

The Input Dialog

The Input dialog allows you to enter text.

The new options we use are: [19659029] entry : Says Zenity that we want to use an input dialog box.

  • -entry : You can use this if you want to type a suggested value in the text entry box. We use "" to force an empty field. This is not essential, but we wanted to document the option.
  • The full command looks like this:

      answer = $ (zenity --entry --text "Enter Your Keyword" --title "Howe - Too Geek" --entry-text = ""); echo $ Response 

    A simple dialog box with a text entry box appears.

     Zenit input dialog box.

    Someone can enter and edit text. [19659003]   Zenity input dialog box with typed text in the text box.

    When he clicks "OK", the entered value is assigned to the Variable Response. We use echo to print the value of the variables in the terminal window.

     User input word in a terminal window.

    Combine Everything

    Let's put these techniques together and create a functional script. The script performs a hardware info scan and displays the results to the user in a scrolling text window. It can choose a long or short scan type.

    Three types of dialog boxes are used for this script, two of which are new to us:

    • The first is a list dialog box. It allows someone to make a selection.
    • The second is a progress dialog box that informs the user that something is happening and he should wait.
    • The third is a text information window that displays the results to the user.

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

      #! / Bin / bash
    
    # Show hardware list for this computer
    
    TempFile = $ (mktemp)
    
    ListType = `zenity --width = 400 --height = 275 --list --radiolist 
    --title & # 39; Hardware Scan & # 39; 
    --text & # 39; Select the scan type: & # 39; 
    --column & # 39; Select & # 39; 
    - Column & # 39; Scan Type & # 39; TRUE "Short" FALSE "Long" `
    
    if [[ $? -eq 1 ]]; then
    
    # You pressed Cancel or closed the dialog box
    zenity --error --title = "Scan rejected" --width = 200 
    --text = "Hardware scan skipped"
    Exit 1
    
    elif [ $ListType == "Short" ]; then
    
    # They chose the short radio button
    Flag = "- short"
    
    otherwise
    
    # You have selected the long radio button
    Flag = ""
    fi
    
    # Search for hardware information with the appropriate value in $ Flag
    hwinfo $ Flag | tea> (zenity --width = 200 --height = 100 
    --title = "compile information" --progress 
    --pulsate --text = "Hardware is being checked ..." 
    --auto-kill --auto-close)> $ {TempFile}
    
    # Display the hardware information in a scroll window
    zenity - width = 800 - height = 600 
    --title "Hardware Details" 
    --text-info --filename = "$ {TempFile}"
    
    exit 0 

    Use this command to make the file executable:

      chmod + x hardware-info.sh 

    This script creates a temporary file and the name of the file is written in TempFile Variable:

      TempFile = $ (mktemp) 

    The script uses the option - list to create a zenity dialog box, called a list dialog box becomes. The characters "" at the end of the lines instruct the script to treat them as a long-dashed line. Here is the procedure:

    • We specify a width and height for the window.
    • The list dialog box supports columns. The option - Radiolist causes the first column to be a column with radio buttons.
    • We set a title and a text prompt for the window.
    • We set the title of the first column to "Select". The contents of this column are the radio buttons.
    • We set the title of the second column to "Select" and specify the content of the second column. This column contains two text names: "Short" and "Long". The TRUE and FALSE indicators mean that the Short option is selected by default when the dialog box appears.
    • We store the result of this dialog box in a variable named ListType .
      ListType = `zenity --width = 400 --height = 275 --list --radiolist 
    --title & # 39; Hardware Scan & # 39; 
    --text & # 39; Select the scan type: & # 39; 
    --column & # 39; Select & # 39; 
    - column & # 39; Scan Type & # 39; TRUE "Short" FALSE "Long" `

    If the user presses" Cancel ", we do not have to check the value in ListType, we can just quit . If he presses "OK", we need to find out if he has selected the radio button "Short" or "Long":

    • The special parameter $? is zero when the user presses "OK". It's almost one when he clicks Cancel or closes the window.
    • If it is equal to one, the script displays an error information dialog box and exits. When he presses "OK", we test the value in the variable ListType .
    • If the variable ListType contains the value "Short", the script sets a variable called flag as equal to "-short".
    • If the variable ListType does not contain the value "Short", it must contain the value "Long", a variable named flag with the value "", which is an empty string ,
    • The script uses the variable flag in the next section.
      if [[ $? -eq 1 ]]; then
    
    # You pressed Cancel or closed the dialog box
    zenity --error --title = "Scan rejected" --width = 200  --text = "Hardware scan skipped"
    Exit 1
    
    elif [ $ListType == "Short" ]; then
    
    # They chose the short radio button
    Flag = "- short"
    
    otherwise
    
    # You have selected the long radio button
    Flag = ""
    fi 

    Now that the script knows what kind of scan the user wants, we can do the hardware information scan:

    • The script calls the command hwinfo and passes it the value in . Variable Flag .
    • If contains flag "-short", the command hwinfo performs a short scan. If the value of flag is "", nothing is passed to hwinfo and a default long scan is performed.
    • The script forwards the output of hwinfo . in tee . tee sends the issue in zenity and in TempFile .
    • The script creates a progress bar dialog box. Sets the width and height of the dialog box, as well as the title and prompt texts.
    • The script can not know in advance how much information the hwinfo command will deliver, and therefore can not correctly advance the progress bar to 100 percent. The option - Pulsing causes the progress dialog to display a moving display. This informs the user that something is happening and he should wait.
    • The option - Auto finish exits the script when someone clicks Cancel.
    • The option - Auto-close The option causes the progress dialog to be automatically closed when the process performed by the monitor is completed.
      # Search for hardware information with the appropriate value in $ Flag
    hwinfo $ Flag | tea> (zenity --width = 200 --height = 100 
    --title = "compile information" --progress 
    --pulsate --text = "Hardware is being checked ..." 
    --auto-kill --auto-close)> $ {TempFile} 

    When the scan hwinfo completes, the script calls zenity to open a text information dialog box with the one Create - Textinfo Option. The text information dialog box displays the contents of the TempFile file:

    • The script sets the width and height of the dialog box and the title text.
    • The filename [19459005MitderOption] reads the contents of the file stored in the variable TempFile .
      # Displays the hardware information in a scroll window
    zenity - width = 800 - height = 600 
    --title "Hardware Details" 
    --text-info --filename = "$ {TempFile}" 

    When the user closes the text information dialog box, the script ends.

      exit 0 

    Let's start and take a look. [19659015] ./ hardware-info.sh

    The list box is displayed. The Short option is selected by default.

     Dialog Box

    Select "Long," and then click "OK."

     Dialog Box

    The progress window is displayed with a slider. It stays on the screen until the hardware scan is complete.

     Progress window with shift indicator.

    When the hardware scan completes, the text information dialog box displays details from the scan.

     Hardware scan information in a text info dialog box.

    Klicken Sie auf "OK".

    Selbst ein eingefleischter Befehlszeilen-Jockey muss einige GUI-Dialogfenster zulassen ein bescheidenes Bash-Drehbuch eine professionelle Note.




    Source link