Creating User Interfaces with yad, dialog, and xdialog
local graph
Chapter 16 — Creating User Interfaces with yad, dialog, and xdialog
Section titled “Chapter 16 — Creating User Interfaces with yad, dialog, and xdialog”I know, you’re thinking that shell scripting consists of nothing but entering boring, plain-text commands in a terminal. But, what if I told you that you can fancy up your scripts by adding a user interface? What if I told you that you can have a graphical interface for desktop systems or a non-graphical interface for text-mode servers? Well, you can, and I’m here to show you how.
Topics in this chapter include:
- Creating a graphical user interface with yad
- Creating user interfaces with dialog and xdialog
If you’re ready, let’s get started.
Technical Requirements
For yad and xdialog, you’ll need to use a desktop implementation of Linux. It doesn’t much matter which distro you use, as long as the yad and xdialog packages are in the repository. Just use your distro’s normal package management tool to install them. (The yad and xdialog packages are also available for GhostBSD, which is FreeBSD with either the Mate or Xfce desktop environment. If you’re on a Mac, you’ll need to install yad or xdialog via Homebrew. Alas, neither one is available for OpenIndiana, and yad isn’t available for any of the RHEL 9-type distros.)
For the dialog section, you can use either a desktop or a text-mode server implementation of Linux.
And, as always, you can grab the scripts by running:
git clone https://github.com/PacktPublishing/The-Ultimate-Linux-Shell-Scripting-Guide.gitOkay, let’s begin by looking at yad.
Creating a Graphical User Interface with yad
Section titled “Creating a Graphical User Interface with yad”Yet Another Dialog, or yad for short, is a very cool program that allows you to add GUI-type interfaces to your shell scripts. There’s a lot you can do with it, and I’d like to show you a few simple examples.
The yad Basics
Section titled “The yad Basics”In the yad man page, you’ll see a list of pre-defined components that you can use in your yad scripts. For example, if you do yad —file, you’ll open the file manager that looks like this:
donnie@fedora:~$ yad --fileFigure 16.1: The yad file manager
As it is, this file manager won’t do anything for you. If you click on a file and then click the OK button, the manager will close and the name of the file that you chose will print out on the command line, like this:
donnie@fedora:~$ yad --file/home/donnie/win_bentley.pdfdonnie@fedora:~$To make this useful, you’ll need to add code that will perform some desired action upon the chosen file. Before we attempt something this complex though, let’s begin with something that’s a bit more simple.
Creating Data Entry Forms
Let’s say that you’re a collector of classic automobiles, and you need to create a simple database to keep track of your vast collection. We’ll begin by testing the basic script, which looks like this:
#!/bin/bashyad --title="Classic Autos" --text="Enter the info about your classic auto:" --form --width=400 --field="Year":NUM --field="Make" --field="Model" --field="Body Style" >> classic_autos.txtThat’s a bit hard to read, though. So, let’s make the yad-form-auto1.sh script a bit more readable, like this:
#!/bin/bashyad --title="Classic Autos" --text="Enter the info about your classic auto:" \--form --width=400 \--field="Year":NUM \--field="Make" \--field="Model" \--field="Body Style" >> classic_autos.txtThis yad command is actually one long command. To make it more readable, I’ve broken it up over several lines, by adding a backslash after each option definition. You could leave out the backslashes and just place the entire command on one line, as you saw above, but this looks much better.
On the first line, I’ve placed both the —title and the —text definitions, which should be self-explanatory. The second line defines a form with a width of 400 pixels. Following that are the definitions for the data entry fields. Note that the Year field can only accept a numerical value, as indicated by the :NUM parameter. At the end, I’m redirecting the output into the classic_autos.txt file. (I’m using the >> operator so that I can add more than one auto to the file.) Here’s how it looks when I run the script:
Figure 16.2: Running yad-form-auto1.sh
When I hit the OK button, the output will be saved to the classic_autos.txt file, which will look like this:
donnie@fedora:~$ cat classic_autos.txt1958|Edsel|Corsair|2 door hardtop|donnie@fedora:~$By default, yad uses the | symbol as the output field separator. That’s okay, because if you open this file in a spreadsheet program, you can set the | symbol as the field separator, and it will work just fine. But, you can change the field separator if you like. For example, if you want to create .csv files, just add the —separator=”,” parameter to the —form line.
One slight problem with this script is that every time you hit the OK button to create an entry in your text file, the script will exit. Each time you add an auto, you’ll need to invoke the script again. Let’s fix that with a while loop, as you see here in the yad-form-auto2.sh script:
#!/bin/bashwhile :doyad --title="Classic Autos" --text="Enter the info about your classic auto:" \--form --width=400 \--field="Year":NUM \--field="Make" \--field="Model" \--field="Body Style" \--field="Date Acquired":DT >> classic_autos.txtdoneBy using a : as the while condition, we’re creating what’s known as an infinite loop. In other words, this will never quit until you press Ctrl-c.
While I was at it, I added the Date Acquired field with the :DT option. This option causes a handy-dandy calendar to pop up whenever I click on the calendar icon. Here’s how it looks:
This is good, but it’s still not perfect. Due to using a : for the while condition, the only way to end this script is to Ctrl-c out of it, because the Cancel button won’t do anything. To fix that, you need to understand that the OK button returns a 0 as the exit code, and the Cancel button returns a 1 as the exit code.
If you need to review the concept of exit codes, refer back to Chapter 8, Basic Shell Script Construction.
Here’s the while loop in this yad-form-auto3.sh script:
#!/bin/bashwhile [ $? == 0 ]doyad --title="Classic Autos" --text="Enter the info about your classic auto:" \--form --width=400 \--field="Year":NUM \--field="Make" \--field="Model" \--field="Body Style" \--field="Date Acquired":DT >> classic_autos.txtdoneThe $? == 0 parameter retrieves the exit code and verifies that it’s 0. This keeps the script running as long as you don’t click on either the Cancel button or the X at the top corner of the window. (I forgot to mention that hitting the X returns an exit code of 252.)
Now, let’s wrap this section up with one last modification.
Creating a Drop-down List
Section titled “Creating a Drop-down List”This time, we’ll add a drop-down list for choosing the body style, and a free-form text box. Here’s the yad-form-auto4.sh script to show you how it’s done:
#!/bin/bashbodystyles=$(echo "2 door hardtop,2 door sedan,4 door hardtop,4 door sedan,station wagon,convertible,pickup truck,other")while [ $? == 0 ]doyad --title="Classic Autos" --text="Enter the info about your classic auto:" \--form --width=400 --item-separator="," \--field="Year":NUM \--field="Make" \--field="Model" \--field="Body Style":CBE \--field="Date Acquired":DT >> classic_autos.txt \--field="Add any additional notes":TXT \" " " " "$bodystyles" "Click on the calender icon"doneThe bodystyles= line, the —item-separator parameter in the —form line, and the ” ” ” ” line all work together to create the drop-down list. The bodystyles= defines the list of available body styles, separated by commas. This goes along with the —item-separator parameter, which ensures that the drop-down list appears with only one body style per line, instead of having all body styles on one line.
The :CBE parameter at the end of the —field=“Body Style” line defines this field as a drop-down list with the option to edit it if you choose the other option. The last line in the while loop tells yad where to place the values of the bodystyles variable. We see that the Body Style field is the fourth field. So to represent the first three fields, which are blank by default, we place three pairs of double quotes ahead of the $bodystyles variable. The last item on the line places a line of text in the Date Acquired field. The final field definition is the free-form text box, as you see by the :TXT parameter. (The text box field comes after the drop-down list field, which means that you don’t have to add another pair of double-quotes to be a placeholder.) Here’s how it looks when I choose a body style:
Of course, you can adapt this script for pretty much any purpose. That can include keeping inventories of your own personal collections, store merchandise, or software licenses. (Let your imagination run wild.)
That wraps it up for this demo. Now, let’s manage some files.
Using the yad File Manager
The easiest way to work with files is to create a variable, with its value assigned by a yad command substitution construct. Then, you can do whatever you want with the value of the variable. Let’s see what we can do with that.
Creating a File Checksum Utility
For the first example, let’s say that you want to create a list of files with their sha512 checksums. Here’s the yad-file-checksum1.sh script that does just that:
#!/bin/bashfiletocheck=$(yad --file)sha512sum $filetocheck >> file_checksums.txtClicking on a file assigns the name of that file to the filetocheck variable. We can then use the value of that variable as the argument for the sha512sum command.
Here’s how it looks:
donnie@fedora:~$ ./yad-file-checksum1.shClicking the OK button creates the file_checksum.txt file, which contains the SHA512 checksum of the people.txt file, which looks like this:
donnie@fedora:~$ cat file_checksums.txt0aa501cc947b22c48c8b2bca0e2a9675fad58440133af8794d8e2b51160f72fa6851c6d76a85546938c23ff5bf70b841bd1099ca727b39a59f486348d3ccee50 /home/donnie/people.txtdonnie@fedora:~$That’s great, but as always, we can fancy things up a bit. In the yad-file-checksum2.sh script, we’ll add a while loop so that the Cancel button will work, and also add the ability to choose multiple files. And, while we’re at it, let’s add a file preview feature. Here’s how that looks:
#!/bin/bashwhile [ $? == 0 ]dofiletocheck=$(yad --file --multiple --separator='\n' --add-preview--width=800)sha512sum $filetocheck >> file_checksums.txtdoneThe —multiple and the —separator=‘\n’ options work together. Without the —separator option, the —multiple option will cause all filenames to appear as one long line, with filenames separated by a | symbol. This will cause the sha512sum utility to view that line as a single filename, which will cause an error. Placing a new line after each filename solves the problem. The —add-preview and the —width options should be self-explanatory, so I won’t comment about them. At any rate, here’s how the new script works:
donnie@fedora:~$ ./yad-file-checksum2.shYou can select multiple non-consecutive files by holding down the Ctrl key, or multiple consecutive files by holding down the Shift key. The end result will be a text file that contains the SHA512 sum checks of all the selected files.
I have to confess that there’s something weird going on with this script, and that it has me stumped. When you click on either the Cancel button or the X button, the dialog box will close down as it’s supposed to do. But, for some strange reason the process doesn’t end, which means that the terminal never returns to the command-prompt. I’ve tried performing every unnatural act I could think of to fix that, but to no avail. So, it appears that whenever you run this script, you’ll just have to Ctrl-c out of it when you’re done.
That’s it, let’s move on to the next example.
Creating a GUI Front-end for ImageMagick
Section titled “Creating a GUI Front-end for ImageMagick”Next, let’s see if we can create a GUI front-end for the ImageMagick program that we talked about back in Chapter 13, Scripting with ImageMagick. We’ll begin with the yad-image-resize1.sh script, which looks like this:
#!/bin/bashimageFile=$(yad --file --title="Select the image file" --width=800)dialog=$(yad --title "Image Resize" --form --field="Resize parameter" --field="Quality")size=$(echo $dialog | awk 'BEGIN {FS="|"} { print $1 }')quality=$(echo $dialog | awk 'BEGIN {FS="|"} { print $2 }')convert "$imageFile" -resize "$size" -quality "$quality%" "$imageFile"yad --title="Status" --width=300 --button="OK:0" --text="All done. Yay!"The first line creates the initial file selection window. It then assigns the filename of the selected file to the imageFile variable. Here’s how this initial window looks:
The second line creates the Image Resize window that you’ll use for entering the resize and quality parameters. When you enter your desired parameters, they’ll get stored in the dialog variable as a single line, with the two parameters separated by a | symbol.
The next two lines create the size and quality variables, using the values that are stored in the dialog variable. We need a way to extract each individual parameter, and awk gives us a handy way to do it. Anyway, here’s how the Image Resize window looks:
Next comes the convert line, which performs the actual resizing. You see that it’s using values from the size, quality, and imageFile variables. When I click on the OK button, the resizing process will take place.
The final line creates the Status window, which shows that the process is complete. By default, yad windows have both a Cancel and an OK button. In this case, we only want the OK button, so we override the default behavior by explicitly creating an OK button with the —button option. Here’s how this window looks:
Figure 16.8: the Image Resize window
Figure 16.9: The Status window
Look in your directory, and you should see that the image has indeed been resized.
To give credit where credit is due, I borrowed this script from a Linux Magazine article that was posted way back in 2012, and made a couple of minor tweaks to it. You’ll find the link to the original article in the Further Reading section.
The major flaw with this script is that it overwrites the original graphics file with the resized version. Let’s modify it so that it will save the resized version as a new file with a new filename. Here’s the yad-image-resize2.sh script that does that:
#!/bin/bashimageFile=$(yad --file --title="Select the image file" --width=800 --add-preview)newfilename=${imageFile%.*}suffix=${imageFile: -4}dialog=$(yad --title "Image Resize" --form --field="Resize parameter"--field="Quality")size=$(echo $dialog | awk 'BEGIN {FS="|"} {print $1}')quality=$(echo $dialog | awk 'BEGIN {FS="|"} {print $2}')convert -resize "$size" -quality "$quality" "$imageFile" -delete 1"$newfilename"_resized"$suffix"yad --title="Status" --width=300 --button="OK:0" --text="All done. Yay!"To make this work, I created two new variables and used variable expansion to assign them their values. The newfilename={imageFile%.*} line grabs the first part of the imageFile filename, up to the dot for the filename extension. For example, let's say that the value of imageFile is somegraphic.jpg. Using variable expansion to strip off the .jpg would result in assigning a value of somegraphic to the newfilename variable. The suffix variable uses the offset feature of variable expansion. In this case, the {imageFile: -4} construct grabs the last four characters of the filename. This results in assigning a value of .jpg to the suffix variable.
The next thing to note is how I had to modify the convert command. (By the way, note that this convert command is quite long, and wraps around on the page.) All I did was to add the -delete 1 “suffix” part to the end of the command that I had before. You’ve probably figured out that with our current example, this would create a new file with the filename, somegraphic_resized.jpg. But, you might be puzzled by the -delete 1 part. Well, it’s just that under certain conditions, the convert command will create two output files, instead of just one, as you see here:
donnie@fedora:~/Pictures$ ls -l *dup*-rw-r--r--. 1 donnie donnie 2324036 Feb 11 14:38 S1340003-dup.JPG-rw-r--r--. 1 donnie donnie 29745 Feb 11 15:57 S1340003-dup_resized-0.JPG-rw-r--r--. 1 donnie donnie 293424 Feb 11 15:57 S1340003-dup_resized-1.JPGdonnie@fedora:~/Pictures$Adding the -delete 1 parameter just before the output filename parameter eliminates that problem, as you see here:
donnie@fedora:~/Pictures$ ls -l *dup*-rw-r--r--. 1 donnie donnie 2324036 Feb 11 14:38 S1340003-dup.JPG-rw-r--r--. 1 donnie donnie 29745 Feb 11 16:00 S1340003-dup_resized.JPGdonnie@fedora:~/Pictures$The final modification I’ll show you, which I’ll put in yad-image-resize3.sh, causes the file manager to only display certain file types. Since we’re dealing with graphics files, we only want the file manager to show us files with the .JPG, .jpg, .PNG, and .png filename extensions. We’ll do that by just adding the —file-filter “Graphics files | *.JPG *.jpg *.PNG *.png”) option to the imageFile= line that’s at the top of the script. The new line now looks like this:
imageFile=$(yad --file --title="Select the image file" --width=800 --add-preview --file-filter "Graphics files | *.JPG *.jpg *.PNG *.png")Now that the line is quite long, let’s make it more readable by breaking it up with backslashes, like so:
imageFile=$(yad --file --title="Select the image file" \--width=800 --add-preview \--file-filter "Graphics files | *.JPG *.jpg *.PNG *.png")That looks much better, right?
All right, let’s move on to our final example.
Programming Form Buttons
Section titled “Programming Form Buttons”In this scenario, we’re in a software developer’s shop that’s running a small fleet of Fedora Linux-powered workstations. We want to create a GUI-type setup utility that will simplify the process of setting up a new workstation. Furthermore, we want to carry this utility around on a USB memory stick so that we can either run it directly from the memory stick, or copy it to each workstation. Fortunately, that’s easy with yad. Here’s the yad-system-tool.sh script that does that:
#!/bin/bashyad --title "System tools for a Fedora Workstation" --form --columns=3 \--width=540 --height=190 \--text="Tools for setting up Fedora or RHEL-type distros" \--field="<b>Update System</b>:FBTN" "dnf -y upgrade" \--field="<b>Authoring and Publishing</b>:FBTN" "dnf -y groupinstall \--with-optional 'Authoring and Publishing'" \--field="<b>Development Tools</b>:FBTN" "dnf -y --with-optional \groupinstall 'Development Tools'" \--button=Exit:1In this script, you see some options that you haven’t seen before. The —columns=3 option in the first line means that we want to create a form with three buttons across on each row. On the second line, you see a —height option, as well as a —width option. In each of the —field lines, you see the :FBTN option, which defines the fields as programmable buttons. The and tags that surround the button text make the button text appear in bold type. The final portion of each —field line consists of the command that will run when you click on the button.
The first button is programmed to perform a system update with the dnf -y upgrade command. The -y causes the command to run without stopping to prompt the user about whether he or she really wants to do it. I had to use the -y option, because without it, the operation would abort at the prompt. The next two buttons each install a selected group of software packages. If you want to see what’s in each of these groups, just run these two commands:
donnie@fedora:~$ sudo dnf group info "Authoring and Publishing"donnie@fedora:~$ sudo dnf group info "Development Tools"Once we’re dealing with administrative commands in this script, we’ll need to run it with sudo. Here’s what it looks:
donnie@fedora:~$ sudo ./yad-system-tool.shNow, just click on a button and watch what happens.
Adding more software installation choices is easy, by just adding more —field lines. If you want to see the list of software packages that are available on Fedora, just do:
donnie@fedora:~$ sudo dnf group listI know, you’re thinking that this type of chore would be more easily accomplished with a set of plain, text-mode scripts. And yeah, you’re right. So, just think of this example as a template that you can use for your own purposes.
Also, I neglected to mention before that you’ll need to manually install yad on each system that you want to administer with this script.
That wraps things up for this script, so let’s move on.
Some Final Thoughts about yad
Section titled “Some Final Thoughts about yad”yad is a really cool program, and you can do a lot of really cool stuff with it. In fact, a person could probably write a whole book on nothing but yad. I can’t do that at the moment, but I’ve hopefully given you enough to whet your appetite.
The main problem with yad is that for whatever reason, its creator has never written any real documentation for it, other than a very sparse man page. Fortunately, a lot of other people have taken up the challenge, and have created their own documentation and tutorials on both the web and on YouTube. (I’ll link to some of these resources in the Further Reading section.)
Next, let’s turn our attention to dialog and xdialog, which we can also use to create user interfaces for our scripts.
Creating User Interfaces with dialog and xdialog
Section titled “Creating User Interfaces with dialog and xdialog”Another slight problem with yad is that you can only use it on machines that have a desktop environment installed. But, many Linux, Unix, and Unix-like servers are set up with a full text-mode environment and don’t have to use graphical desktops. Another slight problem with yad is that even on desktop-type operating systems, it’s not always available for installation. However, if yad isn’t available and you still need a GUI solution, you might be able to use xdialog, which is more universally available. Let’s begin with a look at dialog, which can be used on text-mode machines.
The dialog Basics
Section titled “The dialog Basics”dialog used to be installed by default on all Linux systems, but it no longer is. However, it’s available for installation for pretty much every Linux distro. So, you can install it with your distro’s normal package manager. On most Unix and Unix-like systems, such as OpenIndiana and FreeBSD, it still comes installed by default.
The basic dialog building blocks are known as widgets. Each widget has a set of parameters that you need to specify when you use it. For example, open the dialog man page and scroll down to the —msgbox paragraph, where you’ll see this:
--msgbox text height widthSo, this widget requires you to specify three parameters. (Unlike yad, specifying the dimensions of a dialog box isn’t optional.) Let’s see how that looks in the dialog-hello.sh script:
#!/bin/bashdialog --title "Dialog message box" \--msgbox "\n Howdy folks!" 6 25As you’ve seen before in the yad section, I used a backslash to break the command into two lines, which makes things a bit more readable. On the —msgbox line, we see the message text, the height as defined by the number of rows in the box, and the width as defined by the number of characters that fit on a line.
Running the script looks like this:
Figure 16.11: Running the dialog-hello.sh script
To close the window, just hit the Enter key, which activates the OK button by default. (On a desktop machine, you also have the option of clicking on the OK button with your mouse.) Once the window is closed, run the clear command to remove the blue background from your terminal.
By default, dialog windows always appear in the center of your terminal, and the blue background won’t clear until you clear it yourself. Fortunately, you can change both behaviors. Here’s a slightly modified version of our script, which places the window at the top left corner of the terminal:
#!/bin/bashdialog --title "Dialog message box" \--begin 2 2 \--msgbox "\nHowdy folks!" 6 25clearHere’s how that looks:
The —begin option takes two parameters. The first one denotes the vertical position of the box, and the second one denotes the horizontal position. For example, by changing the line to —begin 15 2, the box would show up in the lower left corner. To place it into the upper right corner, you could change it to —begin 2 50. The clear command at the end will clear away the blue background when you hit the OK button.
Of course, this script isn’t very useful, but that’s okay. I’ll show you some more useful concepts in just a bit. First though, allow me to say a few words about xdialog.
The xdialog Basics
If you need a GUI-type of user interface and yad isn’t available for your desktop system, xdialog could be a good alternative. (I say could be, because neither yad nor xdialog is available for OpenIndiana.) It should be in the normal repository of your Linux or Unix-like distro, so just use your normal package manager to install it. The reason I can talk about both dialog and xdialog in the same section is because for the most part, code that’s written for dialog can also run with xdialog.
There’s one thing to look out for that could trip you up. For some strange reason, the package name is xdialog, in all lower-case letters. But, after it’s installed, you’ll need to invoke the program by typing Xdialog, with an upper-case X. (After I installed it, it took me a while to figure out why I couldn’t get it to work.)
For the most part, changing a dialog script to run as a GUI-type program is a simple matter of changing all instances of dialog to Xdialog, as you see here:
#!/bin/bashdialog --title "Dialog message box" \--begin 2 50 \--msgbox "\nHowdy folks!" 6 25clearRunning the script on a desktop system gives you this:
Figure 16.13: Running the script with xdialog
The first thing to note is that xdialog ignores the —begin option, and just places the box in the center of the terminal. There’s also the fact that xdialog often requires you to create boxes with larger dimensions so that you can see everything. So, let’s change that in the final xdialog-hello.sh script, like this:
#!/bin/bashXdialog --title "Dialog message box" \--begin 2 2 \--msgbox "\nHowdy folks!" 15 50clearAs you see here, this makes things look much better:
With xdialog, the clear command at the end of the script is no longer necessary, but it doesn’t hurt anything to leave it. In fact, we’ll need it for the next demo.
Automatically Choosing Either dialog or xdialog
Now, here’s something that’s really cool. With only a few extra lines of code, you can make your script automatically detect whether it’s running on a desktop or text-mode machine, and whether xdialog is installed. Here’s the xdialog-hello2.sh script to show how it works:
#!/bin/bashcommand -v Xdialogif [[ $? == 0 ]] && [[ -n $DISPLAY ]]; thendiag=Xdialogelsediag=dialogfi$diag --title "Dialog message box" \--begin 2 2 \--msgbox "\nHowdy folks!" 15 50clearThere are several ways to detect if a program is installed. In Chapter 12, Automating Scripts with here Documents and expect, I showed you this method in the system_info.sh script:
if [[ -f /usr/local/bin/pandoc ]] || [[ -f /usr/bin/pandoc ]]; then pandoc -o sysinfo.pdf sysinfo.html rm sysinfo.htmlfiThe pandoc executable that we needed is in the /usr/local/bin/ directory on FreeBSD, and in the / usr/bin/ directory on everything else. So, I set up this if..then construct to detect if the executable is in either place. That works, but I’d now like to show you an easier way.
In the xdialog-hello2.sh script, the command -v Xdialog command detects if the Xdialog executable file is present, regardless of which directory it’s in. If it is, the command will return exit code 0. If it’s not, the command will return exit code 1. To see how this works, go ahead and run this on the command line. Here’s how it looks if the Xdialog executable isn’t detected:
donnie@ubuntu2204:~$ command -v Xdialogdonnie@ubuntu2204:~$ echo $?1donnie@ubuntu2204:~$And, here’s how it looks if it is detected:
donnie@fedora:~$ command -v Xdialogdonnie@fedora:~$ echo $?0donnie@fedora:~$In the next line, you see an if..then construct that checks for two things. First, it checks the exit code from the command command, and then it checks to see if a graphical desktop environment is installed. If the value of the DISPLAY environmental variable is of a non-zero length, then a desktop environment is installed. You can see how this works by running the echo $DISPLAY command yourself. Here’s how it looks on a desktop machine:
donnie@fedora:~$ echo $DISPLAY:0donnie@fedora:~$On a text-mode machine, you’ll get no output at all, as you see here on this Ubuntu Server virtual machine:
donnie@ubuntu2204:~$ echo $DISPLAYdonnie@ubuntu2204:~$For our purposes, we can say that the value of DISPLAY is zero characters long on this text-mode machine.
Now, let’s take another look at our if..then statement:
if [[ $? == 0 ]] && [[ -n $DISPLAY ]]; then diag=Xdialogelse diag=dialogfiThis means that if the exit code from the command -v Xdialog line is 0, and the value of the DISPLAY environmental variable is of a non-zero length, then the value of the diag variable becomes Xdialog. If either the Xdialog executable is missing or the value of DISPLAY is not a non-zero length, then the value of diag becomes dialog. What makes this even more cool is that this works the same on all Linux, Unix, or Unix-like systems. I’ve tested this script on FreeBSD, GhostBSD, DragonflyBSD, OpenIndiana, and on both desktop and text-mode implementations of Linux. On all of them, the script correctly detects everything that it’s supposed to detect, and correctly chooses whether to run either dialog or Xdialog.
Here’s something that caused me a bit of consternation. I accidentally found out that the order in which you test for things sometimes matters. In the if..then construct of this script, I originally checked for the value of DISPLAY first, and then checked for the exit code of the command command. The script wouldn’t run correctly like that, because the test for the DISPLAY value was setting the exit code to 0. When I reversed the order of the tests, everything began to work correctly.
Go ahead and try running this script on a variety of systems, just to see what happens.
Next, let’s build on what we’ve already done by adding another widget.
Adding Widgets
Section titled “Adding Widgets”You can add more functionality by adding more widgets. Take for example the dialog-hello2.sh script, which you can download from the Github repository. I can’t show the entire file at once due to formatting constraints, so I’ll show it to you a section at a time. Here’s the top section:
#!/bin/bashcommand -v Xdialogif [[ $? == 0 ]] && [[ -n $DISPLAY ]]; then diag=Xdialogelse diag=dialogfiWe’ve already seen this in the previous script, and I’ve already explained it. So, let’s move on. Here’s the next section:
$diag --title "Dialog message box" \<!-- page: 442 (printed 440) -->--begin 2 2 \--msgbox "\n Hello world!" 20 50$diag --begin 4 4 --yesno "Do you believe in magic?" 0 0The first diag line creates a box with two buttons that are labeled as Yes and No. The begin 4 4 option positions the yesno box just slightly lower and slightly more to the right of where the initial message box was. After —yesno, we see the text that we want the box to display and the height and width parameters. (Setting the height and width to 0 and 0 causes the box to size itself automatically.)
Next, we have a case .. esac construct that assigns commands to the two buttons. Remember that when clicked, the Yes button returns exit code 0, and the No button returns exit code 1. Pressing the Esc key returns exit code 255. We can use these exit codes to trigger a desired command, as you see here:
case $? in0) clear echo "Cool! I'm glad that you do." ;;1) clear echo "I'm sorry that you live such a dull life." ;;255) clear echo "You pressed the ESC key." ;;esacOkay, all this script does is display a message when you press a button. But, it does serve to demonstrate the concept, so it’s all good.
You’ve already seen the initial message box, so I won’t show that again. Instead, I’ll show the yesno box that comes up next:
Figure 16.15: The yesno box
When I click the Yes button, I’ll see the appropriate message, as you see here:
Figure 16.16: After clicking on the Yes button
And of course, this script runs equally well with xdialog on a machine that supports it.
Next, let’s create something that will actually do some useful work for us.
Creating an SSH Login Interface
Let’s say that you have a fleet of Linux, Unix, or Unix-like servers that you need to administer remotely via SSH. Trying to keep track of the server IP addresses is a confusing mess, so you’ve decided to simplify things. You’ve decided to create the xdialog-menu-test.sh to help you out. It’s also too long to show here in its entirety, so I’ll break it up into sections. Here’s the top part:
#!/bin/bashcommand -v Xdialogif [[ $? == 0 ]] && [[ -n $DISPLAY ]]; then diag=Xdialogelse diag=dialogfiThis is the same as it was in the previous script, so you already know about it. Here’s the next section:
cmd=($diag --keep-tite --menu "Select options:" 22 76 16)options=(1 "Remote SSH to Debian miner" 2 "Remote SSH to Fedora miner" 3 "Remote SSH to Fedora Workstation" 4 "Remote SFTP to Fedora Workstation")choices=$("${cmd[@]}" "${options[@]}" 2>&1 >/dev/tty)The cmd= line creates a command within a pair of parentheses, and then assigns that command to the cmd variable array. This command, which will be invoked in the final line of the script, will build either a dialog or xdialog menu window. According to the dialog man page, the —keep-tite option is desirable when running the script in a graphical terminal emulator on a desktop machine, because it prevents the script from switching back and forth between the graphical terminal and the underlying shell terminal. After the —menu option, we see the text that is to be displayed, the height and width of the menu box, followed by the maximum number of menu entries that will be displayed at a time. (In this example, the user would need to scroll down to see past the first 16 menu entries.) The menu entries would be designated with a tag and an item string. For example, the first menu entry we see has a 1 as the tag, and Remote SSH to Debian miner as the item.
Next, we have the options stanza, which inserts all of the menu entries into an array. The choices= line uses the 2>&1> redirection operator to dump the contents of the array onto the terminal screen (/dev/tty). The @ in ${options[@]} is a form of variable expansion, because it allows an action to be carried out according to which menu item that a user chooses. The @ represents the index number of the array item that corresponds with a menu choice.
In Chapter 8, Basic Shell Script Construction, I showed you how to use either the * or the @ in place of a specific index number to show all elements in an array. In the cmd= line, each component of the $diag —keep-tite —menu “Select options:” 22 76 16 command that’s within the parentheses is a separate element of the cmd array. For this reason, we need to use either the * or the @ as the index for the cmd array in the choices= line at the bottom, so that the entire command will get invoked. The same thing is true for the list of options that get assigned to the options array in the options= line, as you’ll see in a moment.
Now that we have a menu, we need to make it do something. That comes in the next section, which you see here:
for choice in $choicesdo case $choice in 1) ;; 2) ;; 3) ;; 4) sftp [email protected] ;; esacdoneThis is nothing that you haven’t seen before. It’s just a normal for loop that operates a case..esac construct. What is a bit different is that the value of the choices variable is the index number of the array item that corresponds with the chosen menu item. Each of the listed options in the options array consists of a number, followed by a complete phrase, such as 1 “Remote SSH to Debian miner”. In this example, the number 1 represents element number 0 of the options array, and the following words in the phrase represent elements 1 through 5. In order for the options to properly display in the menu, you’ll have to invoke the array with either * or @ in place of the index number. Here’s the complete line where that happens:
choices=$("${cmd[@]}" "${options[@]}" 2>&1 >/dev/tty)Since only one index value is ever assigned to choices, the for loop exits after its first run.
Now that everything is built, let’s see if it works. Here’s how it looks using xdialog on GhostBSD with the Mate desktop:
Figure 16.17: The xdialog-menu-test.sh script on GhostBSD
And, here’s the exact same script on Fedora with dialog:
Figure 16.18: The xdialog-menu-test.sh script on Fedora with dialog
When you choose a menu item, the script will open a remote login prompt in the terminal, and then exit. That’s okay, because if you want to connect to multiple remote servers at once, you’ll need to open other terminals anyway.
Of course, you can fancy this script up to make it even more functional. For example, you can configure your SSH client to use different profiles or different encryption keys for different server sessions, and modify the commands in the menu accordingly. Or, you can use this as a template for something else altogether. As I keep saying, let your imagination run wild!
All right, I think that this about does it for yad, dialog, and xdialog. Let’s wrap up and move on.
Summary
Section titled “Summary”As always, we’ve covered a lot of ground in this chapter, and saw some cool stuff. We began with a discussion of yad, and how to use it to create graphical user interfaces for shell scripts. We then looked at how to use dialog to create user interfaces for text-mode environments, and xdialog for graphical environments. As an added bonus, you saw how to create scripts that will run with xdialog on machines that support it, and dialog on machines that don’t.
These actually aren’t the only three utilities that you can use to create user interfaces for your scripts. Other choices include whiptail, cdialog, and zenity. The good news is that once you’ve learned one, switching to another is fairly easy.
Now, you can do more with these utilities than I’ve been able to show you here. On the other hand, none of these utilities is suitable for creating anything that’s really complex. For that, you’ll need to learn a more complex programming language. Regardless, if all you need is a simple interface to make things easier for either yourself or for your users, these utilities can fill the bill.
In the next chapter, we’ll look at how to run shell scripts with option switches. I’ll see you there.
Questions
Section titled “Questions”-
You want to create a graphical user interface for a shell script that will run on a wide variety of Linux, Unix, and Unix-like operating systems. Which of the following utilities would you use for best availability?
a. zenity
b. cdialog
c. xdialog
d. yad
-
Which of the following statements is true about this code snippet?
command -v Xdialogif [[ -n $DISPLAY ]] && [[ $? == 0 ]]; thendiag=Xdialogelse<!-- page: 448 (printed 446) -->diag=dialogfia. It’s good code, and will work just fine. b. It won’t work, because it uses the wrong method to detect if the Xdialog executable is present. c. It won’t work, because it’s not possible to detect if a certain executable is present. d. It won’t work, because having the [[ -n ? always returns a value of 0.
Further Reading
Dress Up Bash Scripts with YAD: https://www.linux-magazine.com/Online/Blogs/Productivity-Sauce/Dress-Up-Bash-Scripts-with-YAD YAD Guide: https://yad-guide.ingk.se/ How to use ncurses widgets in shell scripts on Linux: https://linuxconfig.org/how-to-use-ncurses-widgets-in-shell-scripts-on-linux Designing Simple front ends with dialog/Xdialog: https://linuxgazette.net/101/sunil.html
- Adding dialog boxes to shell scripts: https://www.linux-magazine.com/Issues/2019/228/Let-s-Dialog
- Menu Driven Shell Script - Using Dialog Utility: http://web.archive.org/web/20120318060251/http://www.bashguru.com/2011/01/menu-driven-shell-script-using-dialog.html
- Xdialog Documentation: http://web.mit.edu/outland/share/doc/Xdialog-2.1.2/
Answers
- c
- d
Get This Book’s PDF Version and Exclusive Extras Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page.
Note: Keep your invoice handy. Purchases made directly from Packt don’t require one.