Wednesday, March 3, 2010

Project: Building An All-Text Linux Workstation - Part 12

In this installment, we're going to take a another look at messaging, this time focusing on Internet Relay Chat (IRC).

IRC is a popular text-mode application that finds wide use on a number of platforms.  Of most interest to us, is its use as a tech support tool.  IRC works by allowing a client program talk to a server that is part of an IRC network.  Multiple users connect to the server and organize conversational groups called channels.  Channels are topic-oriented and cater to a wide variety of interests.  The participants of a channel then can converse with one another via a scrolling text display.

The centerim program we recently installed supports IRC in addition to a number of other popular messaging protocols, however, in this installment we will install a dedicated IRC client called irssi.  To install irssi, we simply:

me@linuxbox:~$ sudo apt-get install irssi

To run irssi, we enter the command:

me@linuxbox:~$ irssi

and the initial screen will appear:



The first window displayed by irssi is called the status window.  It is used to display information about server connections and other status messages.  The initial message in the status message is useful as it points us to the program documentation and some specific connection instructions to join the Debian channel at Debian's own IRC server.

As you type, your input is displayed at the bottom of the screen.  Entries starting with a slash character are interpreted as IRC commands and everything else as a message to post.  To connect to the Debian server we type the following command:

/connect irc.debian.org



It will take a few seconds to connect.

By default, irssi will use your system user name as your "nick" or nickname during an IRC session.  It's possible that your user name will conflict with an existing name already registered by a user of that server.  In that case, we will get something like this:



To overcome this problem, we need to choose another nickname.  That is is done by entering this command:

/nick new_nickname

where new_nickname is the name you wish to use.  In the examples that follow, we will use the nickname "linuxbox", but you should make up your own.  We enter:

/nick linuxbox

and if we're successful, the status window will respond:

You're now known as linuxbox

Now that we have a connection to the IRC server, we next need to join a channel.  Channel names start with a the # symbol.  We can join the #debian channel by entering this command:

/join #debian

Next, we will see a list of all the members of the channel scroll by in another window which overlays the status window.



The prompt at the bottom of the screen changes to indicate that we are in a different window.  Within a window, we can use the PgUp and PgDn keys to scroll the window's contents and we can use the Ctrl-p (previous) and Ctrl-n (next) keys to cycle through the available windows.

As we observe the #debian window, it will slowly scroll as members post questions and answers.  If you are not familiar with IRC, you should consult a good tutorial and observe the general practices of the group before jumping in.  Most channels also post links to official guidelines for the channel's use.   You can see the guidelines for the #debian channel here.

To end our session, we enter this command:

/quit

Filtering Output

The default configuration of irssi displays a lot of non-message text in channel windows announcing the comings and goings of members:



To filter this out of a channel, you can use a command like this:

/ignore -channels #debian * JOINS PARTS QUITS NICKS

Saving Your Settings

As you go through the irssi documention, you will see that irssi has a lot of features and capabilities.  After you have changed your settings, such as adding the filter above, you can store your changes by entering the command:

/save

and your changes will be added to the ~/.irssi/config file.

Another Server To Try

Many Linux and FOSS projects have official support channels on Freenode.  You can reach the Freenode server at irc.freenode.net.  Try the #ubuntu, #fedora, etc. channels there.

Further Reading

IRC tutorials:

General IRC background:

Freenode:

irssi documentation:
Other installments in this series: 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Monday, March 1, 2010

dialog

Now that we have covered launching a script from the GUI, it's time to look at how to make our scripts a little more "graphical."  Interestingly, there are a number of tools that we can use to produce user interfaces for shell scripts.  In this installment, we will concentrate on the most mature of these tools, dialog.

The dialog program lets scripts display dialog boxes for user interaction.  It does this in a text-based manner, using the ncurses library.  It can produce a variety of user interface elements and can pass user input back to a script for processing.  The dialog package is not installed by default on most Linux distributions, but is readily available in most distribution repositories.

dialog has been around for a long time and has gone through a number of incarnations.  The current version (which is maintained by the Debian project) contains a number of features not found in earlier versions.

To demonstrate a few of the powers of dialog, we will write a script that displays a series of dialog boxes and provide some ideas of how to work with the output.  We'll start the script with the following code:


#!/bin/bash

# dialog-demo: script to demonstrate the dialog utility

BACKTITLE="Dialog Demonstration"

# message box

dialog  --title "Message Box" \
        --backtitle "$BACKTITLE" \
        --msgbox "This is a message box which simply\
        displays some text and an OK button." \
        9 50

The script invokes the dialog program with a series of options to set the title for the dialog box, the title for the background screen, the dialog box type (in this example a message box), the text to appear in the box and the size of the box (9 lines high by 50 characters wide).  When we run the script we get the following results:



Next we'll add the following code to the end of the script to generate another kind of dialog called a yes/no box.  In addition to the dialog box itself, we will also include some code to act on the results of the user's selection:

# yes/no box

dialog  --title "Yes/No Box" \
        --backtitle "$BACKTITLE" \
        --yesno "This is a yes/no box.  It has two buttons." \
        9 50

# examine the exit status and act on it
case $? in
        0)      dialog --title "Yes" \
                --backtitle "$BACKTITLE" \
                --msgbox "You answered \"Yes\"" \
                9 50
                ;;
        1)      dialog --title "No" \
                --backtitle "$BACKTITLE" \
                --msgbox "You answered \"No\"" \
                9 50
                ;;
        255)    dialog --title "Esc" \
                --backtitle "$BACKTITLE" \
                --msgbox "You pressed Esc" \
                9 50
                ;;
esac

The yes/no box offers the user three choices: yes, no, and a cancel which occurs if the Esc key is pressed.  To select a button, the user my use the Tab key to switch from button to button or, if dialog is being run inside a terminal emulator on a graphical desktop, the mouse may be used to select a button.

dialog communicates the user's choice back to the script via its exit status.  In the code that follows the yes/no box, we evaluate the exit status.  If the yes button is pressed, the exit status is 0, if the no button is pressed, the exit status is 1, and if Esc is pressed, the exit status is 255.




dialog can provide more than just simple button presses.  It can support edit boxes. forms, menus, file selectors. etc.  When returning more complex data, dialog outputs its results on standard error.  To demonstrate how this works, we will insert the following code near the beginning of the script (just after the BACKTITLE=... line) to define a function (read_tempfile) that will display the dialog output:


TEMPFILE=/tmp/dialog-demo.$$

read_tempfile() {

# display what is returned in the temp file

        local tempfile

        # read file contents then delete
        tempfile=$(cat $TEMPFILE)
        rm $TEMPFILE

        # message box to display contents
        dialog --title "Tempfile Contents" \
                --backtitle "$BACKTITLE" \
                --msgbox "The temp file contains: $tempfile" \
                0 0
}

Next, we will add the following code to the end of our script to display a menu box:

# menu

dialog --title "Menu" \
        --backtitle "$BACKTITLE" \
        --menu "This is a menu.  Please select one of the following:" \
        15 50 10 \
        1 "Item number 1" \
        2 "Item number 2" \
        3 "Item number 3" 2> $TEMPFILE

read_tempfile

This code displays a menu containing three items.  Each item consists of two elements; a "tag" which is returned when a choice is made and an "item string" which describes the menu selection.  In the example code above, we see that the first menu item has the tag "1" and the item string "Item number 1."  When we execute the code, dialog displays the following menu:



To capture and display the output of the menu, we redirect the standard error of dialog to the file named in the constant TEMPFILE.  The read_tempfile function assigns the contents of the temporary file to a variable (tempfile) and passes it to dialog to display in a message box.  After the menu is displayed and a selection is made by the user, the message box appears and displays the data returned to the script.

Next, we will add a checklist dialog by adding the following code to the end of the script.


# checklist

dialog --title "Checklist" \
        --backtitle "$BACKTITLE" \
        --checklist "This is a checklist.  Please from the following:" \
        15 50 10 \
        1 "Item number 1" off \
        2 "Item number 2" off \
        3 "Item number 3" off 2> $TEMPFILE

read_tempfile

As we can see, this code is almost the same as the code used to create the menu dialog.  The main difference is that the items in the checklist add a third field called "status."  The value of status may be either "on" or "off" and will determine if a selection is already selected or deselected when the program is run:




The user may select one or more checkbox items by pressing the space bar.

Next, we will add the following code to the end of the script to display a file selector
:

# file selector

dialog  --title "File Selector" \
        --backtitle "$BACKTITLE" \
        --fselect ~/ 10 30 2> $TEMPFILE

read_tempfile

For the file selector, dialog is passed the base directory for the selection (in this example the directory ~/) and the size of selector.  For this example we specify 10 files in the list and a 30 character wide dialog.




I think the file selector is easy to code, but awkward to use.  You move around the dialog with the Tab key and select directories and files with the space bar.

One of the more novel types of boxes provided by dialog is the "gauge" which displays a progress bar.  To try out this feature, we will add this code to the end of the script:


# gauge

# generate a stream of integers (percent) and pipe into dialog

percent=0

while (( percent < 101 )); do
        echo $percent
        sleep 1

        percent=$((percent + 10))
done | dialog --title "Gauge" \
        --backtitle "$BACKTITLE" \
        --gauge "This is a gauge.  It shows a progress bar." \
        0 0

The gauge dialog does not output anything, rather it accepts a stream of integers (representing the percent of completion) via standard input.  To provide this, we create a while loop to generate the stream of integers and pipe the results of the loop into dialog.  When the script runs, the stream of numbers causes the progress bar to advance:



Note too, that we specified the size of the dialog as 0 0.  When this is done, dialog attempts to auto-size the box to fit in the minimum necessary space.

Finally, we'll add another of the novel dialogs, a calendar:


# calendar

dialog  --title "Calendar" \
        --backtitle "$BACKTITLE" \
        --calendar "This is a calendar." \
        0 0 \
        0 0 0 2> $TEMPFILE

read_tempfile
The calendar dialog box is given a date in day month year format.  If the year is specified as zero, as it is in this example, the current date is used.  The user can then select a date and the date is returned to the script.




This concludes our brief look at dialog.  As you can imagine, dialog can be very handy for adding  improved user interfaces for those scripts that require it.  While we have covered its general themes, dialog has many more options and features.  Check out the documentation link below for the complete story.

Further Reading

Documentation for dialog:

Other dialog-like programs:

Wednesday, February 24, 2010

Project: Building An All-Text Linux Workstation - Part 11

Now that we have email working on our system, it's time to consider other types of communication tools, in particular, messaging.  Text messaging is a very common form of communication today, often surpassing email as way of sending short bursts of small messages.  Messaging actually has its roots in early Unix with the development of the write and talk programs in the late 1970s   While both talk and write were used to communicate with multiple users sharing a single machine, messaging today generally involves users scattered all over the globe using the Internet.

There are many popular messaging protocols such as AIM (AOL Instant Messenger), Jabber, MSN, IRC, and others and many client programs that support one or more of these protocols.  Many Linux users are familiar with Pidgin, a graphical, multi-protocol, messaging client.

In this installment, we will install a text-based analog to Pidgin called centerim, a fork of an earlier messaging client program called centericq.

On our Debian workstation, we can easily install centerim this way:

me@linuxbox:~$ sudo apt-get install centerim

After the program is installed, we can invoke it like so:

me@linuxbox:~$ centerim

The first time centerim runs, it displays a two-part configuration screen which is used to configure accounts and other stuff:








To demonstrate centerim in action, we'll configure an AIM account.  On the second configuration screen, we'll scroll down until we get to the AIM protocol:




Next, we'll enter our account information including our AIM screen name and password:




After we have the account defined, we use the right arrow key to select "Done."  Next, centerim displays our chat window:




Pressing the Esc key twice will take you to the top level menu and from there you can go back to the configuration screens (F4) or quit the program (q).

Further Reading

Centerim and centericq:
Historical background on text messaging:
Other installments in this series: 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Friday, February 19, 2010

Launching Shell Scripts In GNOME

Today, we're going to look at how you launch a shell script (or other terminal-based application) in GNOME.  We are all familiar with launching applications from the command line.  There are advantages to this even for graphical applications.  When you launch an application on the command line, you can see what is produced on standard output and standard error, which can sometimes provide valuable diagnostic information.  On the other hand, there is something to be said for double-click convenience as well.

We will write a tiny shell script and then set up GNOME to allow launching the script from a desktop icon.  Here's the script we will use:

#!/bin/bash

# touch_foo - Script to touch the file "foo"

if [ ! -d foo ]; then
    touch foo
    echo "foo is touched."
else
    echo "foo is a directory."
fi

Pretty simple.  This script touches a file name "foo" but if a directory with that name already exists, it displays a message and exits.  We will enter this script into our text editor and save it as ~/bin/touch_foo.

Next we need to create a launcher for the script.  To do this, we right click on the GNOME desktop and select "Create Launcher...":





A dialog box will appear where we can enter information about the launcher:



Since we want to see the script execute, we will select "Application in Terminal," otherwise the script will execute silently in the background:



Next, we give the launcher a name, browse for the script file, and fill in an optional comment:



You may also click on the icon at the right of the dialog box and select another icon for the launcher.  After the dialog box is filled out, we can click the OK button and the launcher is created and it will appear on the desktop.  Double clicking on the new launcher icon launches the script.

But there's a problem.  The terminal appears for an instant and vanishes.  Not exactly what we had in mind.  What gives?

The problem is that when the script finishes, the terminal session ends.  To prevent this, we have to stop the script from finishing.  We could do this by having an endless loop at the end of the script, or by including a read command which will wait for user input before proceeding.  We can adjust our script by adding a line at the end:

#!/bin/bash

# touch_foo - Script to touch the file "foo"

if [ ! -d foo ]; then
    touch foo
    echo "foo is touched."
else
    echo "foo is a directory."
fi

read -p "Press Enter to continue > "

After making this change, a terminal will appear and wait until the Enter key is pressed:


Another Approach

Another way we can configure commands for the launcher is to directly launch gnome-terminal and pass the desired command as an argument.  This allows us to control the configuration of the terminal.  For example we can set the window title, window geometry, and terminal profile used with our command.  Here is a command we can use to launch the top program and set the window title to "Top":

gnome-terminal -e /usr/bin/top -t Top

Note however, that if you want to run shell scripts this way, you must construct the command this way:

gnome-terminal -e 'bash -c touch_foo'

including the bash program in the command so that there is a program present that can interpret your script.

Further Reading
  • gnome-terminal man page
  • bash man page (OPTIONS section)

Wednesday, February 17, 2010

tput

In a recent post, we covered a technique that can produce colored text on the command line.  Today, we will look at a more general approach to producing not only text effects, but also gaining more visual control of our terminal.

A Little History

Back in the old days, when computers were connected to remote terminals, many brands of terminals existed and they were all a little different in terms of their feature sets and capabilities.  As a result, different terminals used different sets of commands to control them.

Terminals responds to codes (called control codes) embedded in the stream of text sent to them.  Some of these codes are standard and familiar like carriage return and line feed.  Others, like those to turn on bold text or underlining are not.  Terminals can, in fact, perform many kinds of functions.  As microprocessors became available and the advent of the personal computer loomed, terminals became increasingly "smart" and feature laden.

However the proliferation of terminal brands and feature sets posed a problem for software developers.  Software had to be painstakingly customized to support a particular terminal.  What was needed was a software system that supported hardware independence so that applications could use a standard set of commands to deal with any terminal.  This problem was addressed in two ways.  First a standard set of control sequences were developed by ANSI (American National Standards Institute) and adopted (in varying degrees) by terminal manufactures to give all terminals a common set of commands.  We looked at the ANSI commands in a an earlier post.  The second approach was development of an intermediary layer (much like today's notion of a device driver) that translates a standardized command into the specific control codes used by a particular terminal.

In the Unix world, there are two such systems, the original, termcap and the more recent terminfo. Both contain a database of control code sequences used by different kinds of terminals.

Enter tput

tput is a command that can query the terminfo database to see if a particular terminal can support a particular feature.  It can also accept terminal commands and output (via standard output) the control code sequences for that terminal.  tput is generally used like this:

tput capname [parameters...]

where capname is the name of a terminal capability and parameters are any option parameters associated with the specified capability.  For example, to output the sequence of instructions needed to move the cursor to the upper left corner of the screen (the "home" position):

tput cup 0 0

which means cursor position row 0, column 0.

Since tput actually outputs the sequence to standard output (you won't see the sequence since it is interpreted by your terminal emulator as an instruction), you can store the sequences in variables.  Here we will store the sequences to control bold text:

bold_on=$(tput bold)
bold_off=$(tput sgr0)

Now, to highlight some text, you could:

echo "This is ${bold_on}important${bold_off}."

and you get this:

This is important.

There are a huge number of terminal capabilities, though most terminals only support a small subset.  Besides changing text colors and positioning the cursor, it is possible to erase text, insert text, and control text attributes.  The terminfo man page lists all the terminal capabilities and the Bash Prompt HOWTO section 6.5 (see "Further Reading" below) describes the ones most useful for ordinary screen control.

Before we leave, here is a version of the prompt_colors script that uses tput to set foreground and background text colors:

#!/bin/bash

# prompt_colors -- demonstrate prompt color combinations.

for fore in {0..7}; do
    set_foreground=$(tput setf $fore)
    for back in {0..7}; do
        set_background=$(tput setb $back)
        echo -n $set_background$set_foreground
        printf ' F:%s B:%s ' $fore $back
    done
    echo $(tput sgr0)
done

Further Reading