July 11, 2009

Extending Hello World

In previous installment I was claiming how shell is powerful, but instead of demonstrating that power I was busy explaining why exclamation sign is causing problems. Now I must show how shell is capable of calling installed software. For example, we introduce personalised version of Hello World where script will call whoami and provide us with personalised greeting.

echo "Hello Mr. `whoami`."

Those 'single quotes' are actually back-ticks, back-tick is in top left corner of the keybord. Then we can add more in the similar fashion:

echo "Hello Mr. `whoami`. Your current directory is "`pwd`" and current date and time is `date`."

It is somehow nice to have path quoted, so that is the reason why we escaped pair of double quotes around pwd. Instead of using back-ticks we may do this:

echo "Date is $(date)."

OK how do we go about interacting with the user?

echo "Hi, please type in your name and hit enter."; read yourname; echo "Hello $yourname, have a nice day."

Here we introduced variable yourname. Function read reads user's input (who would expect that?) and stores it in yourname, to access content of that variable we added '$' in front of it.

From shell we can use GUI dialogs, they are coming from GTK+ and package which we are going to call is called zenity. That is very simple, here is the example:


myname=`zenity --entry –title="Hello dialog" --text="Hi I am HAL9000. What is your name?"`

if [ -z "$myname" ] ; then

echo "User's name is empty string?"



zenity --info --title="Greeting" --text="Hello $myname."

Here we check if the user entered anything into the first dialog, if not, we use user's login and finally greet the user.

If you copy and paste this from a web page, odds are that you will have
as a new line and when you try executing script it may produce the following:


bash: ./dialog3: /bin/bash^M: bad interpreter: No such file or directory

What does it mean? Linux can't find /bin/bash
. To remove evil '
' and keep good '
' do this:

tr --delete '
' < dialog3 > dialog4

Again, the procedure to create script is open gedit copy, paste, save as dialog3 in Documents. In terminal we do:

cd Documents

chmod a+x dialog3


If '
' problem appears, then

tr --delete '
' < dialog3 > dialog4

chmod a+x dialog4


Now is a good moment to take a better look at zenity. I will let you do that at your own pace. The best starting point is zenity man page:

man zenity

Further, there is zenity web page http://library.gnome.org/users/zenity/stable/zenity-introduction.html.en where we can find few examples on how to use it.

Next time we will take a look at some Nautilus scripts and try to create one or two on our own. In no time our Shell-Gnome productivity will be soaring.

Click Here!