More fun with Zenity: shell script/GUI interactivity

More fun with Zenity: shell script/GUI interactivity


In the first part of this piece I introduced zenity : the handy tool for providing GUI interaction with your shell scripts. In this second part I'm going to delve a little deeper into the type of things you can do with this versatile tool.

Not just info dialogs

Zenity can do a lot more than just provide information dialogs -- handy though they are. It has a whole range of dialogs that you can use to get user feedback and decision-making involved with your scripts. Examples include not only the traditional errors, warnings, questions and progress dialogs but things like calendars, text entry, lists and file-selection. Without wanting to become a replica of the zenity manual, let's have a look at some of them.

Errors and warnings

In essence these two are the same as information dialogs but they use a different icon on the dialog itself. This code displays a warning dialog:

zenity --warning --text "Configuration file not found\!\nUsing default settings instead." --title "MyScript warning"

Note the use of \n there to insert a new line character. Also note the use of the title parameter. If you don't supply a custom title zenity will use the dialog type as a title (so in this case that would be "Warning").

Getting some user input

File selection

Suppose your script requires the user to provide a file path -- perhaps (to continue the above example) to load a config file if one could not be found. You can provide a file-selection dialog which will be immediately familiar to the user:

CONFIG_FILE=`zenity --file-selection --title "Select a configuration file"`
case $? in
  0) source $CONFIG_FILE;
  1) zenity --warning --text "No configuration file selected\nUsing default settings"
 -1) zenity --warning --text "No configuration file selected\nUsing default settings"
esac

That snippet provides a file open dialog which returns 0 if the user clicks OK and 1 if they click Cancel. -1 will be returned if something went wrong. By using this in your scripts you can ask the user to provide file paths to be somehow used in your script later. If you want to limit the user to directories and not files, you can add the --directory switch.

Text entry

Another way to get some input is to provide a text entry box. For example this code:

ENTRY=`zenity --entry --text "Please enter your name" --entry-text "Yourname" --title "Enter your name"
if [ $? == 0 ]
then
zenity --info --text "Hello $ENTRY\!"
fi

Note how the --entry-text switch populates the text entry box and pre-selects it for replacement. Not all those switches are required by the way. The simplest form for entry dialogs is zenity --entry and that applies to most other zenity dialogs as well.

Calendar

You're probably getting the hang of this now, but if you need the user to provide a date you can use the --calendar switch by running zenity --calendar. This command will return the date in the short format for your locale (so for my systems that's DD/MM/YYYY). You can preselect dates using the --day, --month and --year switches. The returned format can also be set using standard "strftime" codes:

DATE=`zenity --calendar --day "20" --month "2" --year "2009" --format "%Y-%m-%d"
if [ $? == 0 ]
then
echo $DATE
fi

That will open a dialog with the 20 Feb 2009 selected and the chosen date will be returned as YYYY-MM-DD. Both --day and --month do not accept leading zeros and -year expects four digits. It assumes "89" is the year 89 and not 1989.

Questions

No dialog set would be complete without questions. Zenity provides a simple question dialog with fixed button labels. That means you have to ensure your question text is worded such that it can be reasonably answered with "OK" or "Cancel". So instead of "Proceed without config file?", you might like to say "Config file not found. Click OK to use defaults or Cancel to stop the script." In the case of the former, it can be unclear what Cancel would do: stop the script running or pop-up a dialog insisting on a file path. The latter leaves the user in no doubt. The question dialog returns a 0 if the OK button is clicked and 1 if the Cancel or close buttons are clicked.

Providing feedback to the user

In addition to the info, error and warning dialogs the progress dialog can prove useful in providing feedback to the user. In the first part of this piece I mentioned how I had used zenity to provide a colleague with a GUI interface to a connection script for a 3G mobile broadband connection. In that situation there can be some delay while the modem negotiates with the 3G network for a connection. During that delay I use a progress dialog to let the user know something is happening:

connect.sh up | zenity --progress --text "Connecting, please wait ..." --pulsate

The --pulsate switch is handy here because I am just saying "hold on while I do some stuff". There's not real percentage feedback to give, so this switch has the progress bar pulsate back and forth across the dialog "Knight rider" style. If you need to provide growing progress feedback you can do so by echoing percentages to zenity:

( for FILE in find $START_DIR --name $FILE_NAME;
do
echo 1;
echo $FILE >> $OUTPUT_FILE;
done
echo 100;
echo "#All files now listed in $OUTPUT_FILE"
) | zenity --progress --percentage=0 --text "Finding files..." --title "Find and list files";

Yes I know, there are much simpler ways to put a list of files from a directory into a text file -- it's just an example. The above example also assumes there are no more than 100 files in the directory and -- quite honestly -- the progress bar will be at 100% almost immediately.

That's enough for now

There's a lot more to know about zenity but hopefully this has given you a taster. Zenity's help commands are excellent and there are a number of other online resources that can help as well.

As the number of GNU/Linux users that are unfamiliar with the shell increases, tools like Zenity can make all the difference for those of us helping them. The first part of this piece was called "Saving my sanity with Zenity" and on more than one occasion that is exactly what it has done. Whilst it's true that some GUI tasks require something with greater GUI capabilities, tools like zenity, dialog and kdialog mean that the day of "knocking up a quick shell script" are by no means lost.

Category: 

Author information

Ryan Cartwright's picture

Biography

Ryan Cartwright heads up Equitas IT Solutions who offer fair, quality and free software based solutions to the voluntary and community (non-profit) and SME sectors in the UK. He is a long-term free software user, developer and advocate. You can find him on Twitter and Identi.ca.

Most forwarded

Interview with Dave Mohyla, of DTIDATA

Dave Mohyla is the president and founder of dtidata.com, a hard drive recovery facility based in Tampa, Florida.

TM: Where are you based? What does your company do?
DTI Data recovery is based in South Pasadena, Florida which is a suburb of Tampa. We have been here for over 10 years. We operate a bio-metrically secured class 100 clean room where we perform hard drive recovery on all types of hard disks, from laptop hard drives to multi drive RAID systems.

Anybody up to writing good directory software?

Since the very beginning, directories (of any kind) have had a very central role in the internet. (I have recently grown fond of Free Web Directory. Even Slashdot can be considered a directory: a collection of great news and invaluable user-generated comments. As far as software is concerned, doing a quick search on Google about software directories will return the free (as in freedom) software directories like Savannah, SourceForge, Freshmeat and so on, followed by shareware and freeware sites such as FileBuzz, PCWin Download Center and All Freeware (great if you're looking for shareware and freeware, but definitely less comprehensive than their free-as-in-freedom counterparts).

Interview with Mark Shuttleworth

Mark Shuttleworth is the founder of Thawte, the first Certification Authority to sell public SSL certificates. After selling Thawte to Verisign, Mark moved on to training as an astronaut in Russia and visiting space. Once he got back he founded Ubuntu, the leading GNU/Linux distribution. He agreed on releasing a quick interview to Free Software Magazine.

Is better education the key to finding better software?

I read David Jonathon's article Anybody Up To Writing Good Directory Software? the other day, which got me thinking about software directories in general. As David mentioned, many of the software directories one finds when doing a quick google search are free as in beer, not as in freedom. But what interests me is the software directories that already exist, providing a combination of both free as in beer software, and open source software. Sites such as Freeware Downloads and Shareware Download don't advertise themselves as providing free as in liberty software, but each of them have a good selection of open source software available... if you know where to look.

Most emailed

Free Open Document label templates

If you’ve ever spent hours at work doing mailings, cursed your printer for printing outside the lines on your labels, or moaned “There has got to be a better way to do this,” here’s the solution you’ve been looking for. Working smarter, not harder! Worldlabel.com, a manufacture of labels offers Open Office / Libre Office labels templates for downloading in ODF format which will save you time, effort, and (if you want) make really cool-looking labels

Creating a user-centric site in Drupal

A little while ago, while talking in the #drupal mailing list, I showed my latest creation to one of the core developers there. His reaction was "Wow, I am always surprised what people use Drupal for". His surprise is somehow justified: I did create a site for a bunch of entertainers in Perth, a company set to use Drupal to take over the world with Entertainers.Biz.

Update: since writing this article, I have updated the system so that the whole booking process happens online. I will update the article accordingly!

So, why, why do people and companies develop free software?

More and more people are discovering free software. Many people only do so after weeks, or even months, of using it. I wonder, for example, how many Firefox users actually know how free Firefox really is—many of them realise that you can get it for free, but find it hard to believe that anybody can modify it and even redistribute it legally.

When the discovery is made, the first instinct is to ask: why do they do it? Programming is hard work. Even though most (if not all) programmers are driven by their higher-than-normal IQs and their amazing passion for solving problems, it’s still hard to understand why so many of them would donate so much of their time to creating something that they can’t really show off to anybody but their colleagues or geek friends.

Sure, anybody can buy laptops, and just program. No need to get a full-on lab or spend thousands of dollars in equipment. But... is that the full story?

Fun articles

Santa Claus - the most successful open source project

It dawned on me the other day, as I was shopping for the dozens of gifts it seems I have to buy every December, that Santa Claus is the most successful open source project in history. (Bridget @ Illiterarty would agree with that). Santa Claus is essentially a marketing development that is embodied by everyone who stuffs a sock, gives a gift, hosts a dinner or wishes Merry Christmas over the holiday season.

Most emailed

Editorial

When I first started thinking about Free Software Magazine, I was feeling enthusiastic about the dream. I had Dave, Gianluca, and Alan willing to help me, I had established members of the free software community willing to help me out, I had writers volunteering their time and energy for free, and I had a generous offer from OpenHosting for servers, all before I'd proved myself. There was a sense of excitement in the air, and I thought maybe, just maybe, I could make this work.

Free Software Magazine uses Apollo project management software and CRM for its everyday activities!