Monday, September 29, 2008

Pop-up Dialog in Shell scripts

As I am an old-time computer user, I still prefer doing almost everything from the command line (CLI). I program almost everything in bash-scripts and schedule them with cron.
But of course I do use a graphical interface to read mail (although I have Alpine configured to read my mail from the CLI) and browse the internet (but I also use links a lot!).
Sometimes a bash script needs to give or get feedback, like reporting an error or just telling everything worked fine. Scheduled scripts normally write logs that can be checked later, or can even send e-mails to a user.
There is another, not so well-known option for interaction with the user, if you use KDE as your desktop environment: kdialog
It has many different options to choose from, so I'll give just a few simple examples:

kdialog --title "Hey you..." --yesno "Do you like this popup?"

This pops up the following dialog:


(You'll just have to believe that "Sim" = "Yes" and "Não" = "No" in Portuguese)
The result of which button the user clicked can be obtained by reading the '$?' variable in bash: '0' for the first button (Yes), '1' for the second ('No') and so on.

Another useful example is:

kdialog --title "Warning..." --warningyesno "Low on space on /var - Continue?"

which gives this result:

There are many more options to show radio buttons, check boxes, prompts for passwords, etc.

Now let's use this in a small script:

#!/bin/bash
#
# Sample on how to use kdialog

ERR_SPACE=101

# Calculate needed space
needed=1000 # ok, we're not calculating...

# Calculate space on $dev
dev=/var
space=800

# Test if we have sufficient space left
if [ $space -lt $needed ] ; then
   kdialog --title "Warning..." \
      --warningyesno "Low on space on $dev - Continue?"
   if [ $? -ne 0 ] ; then
      echo "Copy failed" >> log
      exit $ERR_SPACE
   fi
fi

# Copy here...

echo "Copy ok" >> log

# All done

After calling kdialog we test the answer with '$?'. If it is not zero, which means the user clicked on 'no', we exit the script with the defined error code.

For more options, simply enter 'kdialog --help' on the command line.

Happy scripting!

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home