More 2 Cent Tips & Tricks Issue 21

#### "Linux Gazette...making Linux just a little more fun! "

# More 2¢ Tips!

Send Linux Tips and Tricks to gazette@ssc.com

### Contents:

- Changing Video Modes
- Colormap Questions
- Netcat!
- Starting and Stopping Services
- A New Tool for Linux
- Of Logs and Other Things
- Calculator Tip
- Another Way to View Tarred Files
- Script Ease
- Syslog Thing
- Sorta E-mail-to-FAx...Well, to-Printer
- Setting Xterm Title to Current Process
- CVS

### Changing Video Modes

Date: Fri, 08 Aug 1997 22:41:05 -0600
From: Michael J. Hammel mjhammel@csn.net

I don't know how AccelX and XiGraphics and MetroX handle these things.

AccelX is ( I think) a PC graphics company. You might mean Xaccel, which is the actual program name for Xi Graphics X server. Its product name is "AcceleratedX". Xi Graphics is the company name.

As for how Xaccel changes its video modes - try CTRL-ALT-+ (thats a plus sign). I believe that cycles through the various modes. Check the man pages or manual to be certain. I believe MetroX does similar, but the keystroke is probably different.

--

### Colormap Question

Date: Fri, 08 Aug 1997 23:47:31 -0600
From: Michael J. Hammel mjhammel@csn.net

The question was "can you force an X application to use its own colormap in some way other than using a command line option". The answer is: it depends (aint it always the case?).

An applications ability to use its own colormap is not a "builtin" part of X. Colormaps are part of X, but the application still has to add code to make use of colormaps. So if the application doesn't have any code specifically for handling colormaps (for example, my XPostitPlus doesn't have any such code) then neither the command line or any other method will force it to use a private colormap. The default for applications (like XPostitPlus) is to use the default colormap, and thats why you often see applications with weird colors that you can't get rid of till you exit some other application.

Now, if the application *does* have code to deal with colormaps, it can also make the use of the private colormap a user configurable option. X provides a mechanism for making an option either a command line option (eg. -usePrivateColormap) or an X resource. X resources can be specified in X resource files (like .Xdefaults) or on the command line using the -xrm option. X is so configurable that the number of ways for a user to supply configuration information can often be quite confusing, both for the user and the developer. In any case, its up to the programmer to make any of these methods available. None is available by default simply becaue its "an X windows program".

The correct thing for an application to do is to allow the user to configure the use of the private colormap in at least one way and to provide a best-guess default for determining if a private colormap would be the best thing to do or not if the user doesn't provide a preference. Few applications do this, however. The GIMP does. So do XV and Netscape. Even my own programs aren't very good at this, although I intend to get much better in the very near future.

As for an X column, well, I'd love to see one. We just need to convince some X hack to spend a little time writing articles instead of code. Thats kinda hard to do. I'll probably be adding some X coding tidbits to my Muse column, but only with respect to using Motif or OpenGL in graphical and multimedia applications.

Hope this helps a little.

-- Michael

### Netcat!

Date: 01 Aug 1997 15:46 EDT
From: Jean-Philippe Sugarbroad da1wizard@geocities.com

I was going through back issues of the Linux Gazette and I remembered a program I use quite frequently... netcat. This program enables you to open sockets and connect or listen with them - all from a shell script! It's a great way to quickly fetch web pages or see if a server is running... It even has UDP 'connection' mode and zero-io mode (which closes the connection as soon as it succeeds...). The UDP mode even uses a TCP connection to check round-trip time :) I love it!

Jean-Philippe Sugarbroad

### Starting and Stopping Services

Date: Tue, 5 Aug 1997 18:55:19 -0600 (CST)
From: Terrence Martin twm139@its.to

I was just reading the August version of Linux Journal and I noticed refrence to rebooting the system after making changes to the /etc/syslog.conf file in order for those changes to take affect. This is contrary to a feature that is the main reason I use Linux at home and at work.

It is only generally necessary to reboot Linux to add/remove hardware or when installing a new kernel. In the specific case of syslogd(8) you can inform the server to reread it's initialization file by sending it a SIGHUP signal.

    eg.
    kill -HUP `cat /var/run/syslogd.pid`

This will work with many of the servers available for Linux including (most) httpd(8), named(8), and inetd(8).

Sometimes however it is preferable to actually restart these services. In Slackware I believe most of your services are placed in a single script and this makes it a little more difficult to pick and choose which services to stop and start.

In RedHat it is a little more modular. In the directory /etc/rc.d/init.d are the scripts that are run on bootup to start various services.

These scripts allow you to start and stop various services just as if you had shutdown and rebooted your machine. eg.

    # /etc/rc.d/init.d/named.init stop
    # /etc/rc.d/init.d/named.init start

This will start and stop the name service.

The scripts supplied with RedHat are not too complex compared to similar scripts I have seen on other systems. They can usually be adapted to new services that you may wish to have start on bootup, without complicating the rc.local file and giving you much finer control.

If you examine the soft links in /etc/rc.d/rc0.d through /etc/rc.d/rc6.d you will notice that they link to the files in /etc/rc.d/init.d. Each of these numbers on these directories refer to a "runlevel".

As the system boots the /etc/inittab tells the init process which directories to examine to determine which services to start up, most systems not running xdm will end at runlevel 3, otherwise it is runlevel 5.

All of the files(softlinks) in runlevel 3 beginning with 'S' are executed in order of occurance in the directory, this is controlled by giving each a number ie

    S30syslog -> ../init.d/syslog comes before
    S40cron -> ../init.d/cron.init.

Note: Links with the same number are executed in lexical order.

The sequence may be important depending what services depend on other services.

I put most of the services I add in runlevel 3, as I usually boot into multiuser mode. You then should add the approriate script link to /etc/rc6.d as those are the files that are executed on shutdown. Note the convention here is to begin all soft link names with 'K'. ie

    K10named.init -> ../init.d/named.init

Again these scripts are executed on order with the highest number being last to run.

The net effect of all these links is that with an 'S' preceding the soft link the script is run with the argument "start" and with a 'K' it is run with the argument "stop".

Over the last two weeks I have set up and configured a news server, web server, name server, sshd server, updated the syslog.conf file plus a hundred other little tweaks on our RedHat 4.x box and I have not had to reboot once. In fact the system has not been rebooted since we added a new CPU and SCSI card 31 days ago...I love Linux :)...

Regards
Terrence Martin

### A New Tool for Linux

Date: Fri, 22 Aug 1997 08:29:59 -0500
From: Ian Beth13@mail.utexas.edu

The version posted in issue 20 assumes you have exec access to ALL dirs under the one you 'TREE'

Here's a modified version which works even in cases of unreadable folders:

    -------------------------------- cut here --------------
    #!/bin/sh
    #         @(#) tree      1.1  30/11/95       by Jordi Sanfeliu
    #                                         email: mikaku@arrakis.es
    #
    #         Initial version:  1.0  30/11/95
    #         Next version   :  1.1  24/02/97   Now, with symbolic links
    #         Patch by       :  Ian Kjos, to support unsearchable dirs
    #                           email: beth13@mail.utexas.edu
    #
    #         Tree is a tool for view the directory tree (obvious :-) )
    #
    search () {
       for dir in `echo *`
       do
          if [ -d $dir ] ; then
             zz=0
             while [ $zz != $deep ]
             do
                echo -n "|   "
                zz=`expr $zz + 1`
             done
             if [ -L $dir ] ; then
                echo "+---$dir" `ls -l $dir | sed 's/^.*'$dir' //'`
             else
                echo "+---$dir"
                if cd $dir ; then
                   deep=`expr $deep + 1`
                   search    # with recursivity ;-)
                   numdirs=`expr $numdirs + 1`
                fi
             fi
          fi
       done
       cd ..
       if [ $deep ] ; then
          swfi=1
       fi
       deep=`expr $deep - 1`
    }

    # - Main -
    if [ $# = 0 ] ; then
       cd `pwd`
    else
       cd $1
    fi
    echo "Initial directory = `pwd`"
    swfi=0
    deep=0
    numdirs=0
    zz=0

    while [ $swfi != 1 ]
    do
       search
    done
    echo "Total directories = $numdirs"

    -------------------------------- cut here --------------

The changes are to put the "cd $dir" as the predicate of an IF statement, NOT IN A SUBSHELL, and the recursive part is the switched clause. This prevents infinite recursion in the case of an unreadable or unexecable dir.

### Of Logs and Other Things

Date: Sun, 10 Aug 1997 21:47:39 +0200
From: D. Emilio Grimaldo T. grimaldo@panama.iaehv.nl

Hi,
I recently saw on the August issue of Linux Gazzete and some previous issues about the handling of system logs. Well, it doesn't have to be complicated, in fact I have written a very useful script/package that has been around for a couple of years, it is called Chklogs and is used by major network providers, companies and small-time users of Linux systems. In fact it is going to be featured in the Linux Journal some time this year. IT fulfills all the log handling needs. For more information see http://www.iaehv.nl/users/grimaldo/info/

Catch the link to Chklogs

Best Regards,
Emilio

### Calculator Tip

Date: Sun, 27 Jul 1997 23:43:37 +0200 (MET DST) From: Hans Zoebelein zocki@goldfish.cube.net

Hello Linux Gazetters,
Here comes a real cheap command line calculator. Since shell scripts do only integer calculation, you are stuck if you want floating point precision.

You also want to do sometimes stuff like 'how much is 1200*3/7' at the commandline without firing up a full blown GUI calculator.

Just for that work you can use the `calcme` command line calculator, which is hacked in perl. Dont forget that a shell thinks differently about 10*3 than a calculator. So do it as 10\*3 or "10*3".

The icing of the cake is the optional formatting. If you supply something like `%.3f` as second parameter, the output is nicely formatted as floating point number and up/down rounded correctly after 3 decimals.

You also can do a `calc 10/3 %20.6f` which returns a string with 6 digits and 20-6=14 spaces like `______________3.3333`. So formatting of lists in shell scripts is real fun now.

Enjoy!
Hans

    #!/usr/bin/perl

    #
    # The ultimate command line calculator :-^
    # Usage calcme <string_to_calculate> [<output_format>]
    #

    # Input is a string like (10+3)/7 or "(10 + 3) / 7"
    # Output is the calculated result of the string (sic!).
    # Optional formatting can supplied as 2nd parameter.

    if (@ARGV == 0 || @ARGV > 2)
    {
       die("Usage: $0 <\"formula_to_calculate\"> [<output_format>]\n");
    }

    $format = "";
    $calcme = $ARGV[0];
    (@ARGV == 2) && ($format = $ARGV[1]);

    $output = eval($calcme);

    if(@ARGV == 1)
    {
       print(STDOUT "$output\n");
    }
    else
    {
       printf(STDOUT "$format\n", $output);
    }
    exit(0);

-- Hans

### Another Way to View Tarred Files

Date: Sat, 02 Aug 1997 02:18:07 +1000 (GST) From: Gerald J Arce garce@starcommand.mang.net

In issue 19, I read a 2 cents tip regarding viewing a tarred file. I use less instead..

    ex:
    tar tzf foo.tar.gz

    less foo.tar.gz

Less typing (grin).

### Script Ease

Date: Wed, 6 Aug 1997 01:54:19 +0200 (GMT+0200) From: Trucza Csaba ctrucza@cemc.soroscj.ro

Hi all,

As a programmer-wannabe, I do a lot of typing. To ease at least the beginning of each source file (which is mainly the same: include-s, define-s, imports and stuff), I wrote a script to automatize this. For the quality of the script please read the notice at the end of my mail.

    (file: se)
    ---------cut here---------------
    #!/bin/sh
    #
    # 	source editor (se)
    #
    #	usage: se <filename> <type>
    #
    #	WARNINGS:
    #		1. do not supply extension:
    #			se MyProg.java will make a MyProg.java.java!!!
    #
    #		2. manually create the
    #			SE_HOME_DIR,
    #			SE_HOME_DIR/temp,
    #			SE_HOME_DIR/templates
    #
    #	man se:
    #
    #	create two files for each type of the source you want to se.
    #	the script will copy the first file+filename+second file into a new
    #	file (you got it?:-)
    #
    #	so: if you want java, create two files:
    #
    #	templates/java.1:
    #
    #	---8<---
    #	public class
    #	--->8---
    #	(Do not put a newline at the end!)
    #
    #	templates/java.2
    #
    #	---8<---
    #	{
    #		public static void main(String args[]){
    #		}
    #	}
    #	--->8---
    #
    #	the script for se MyProg java (or jus se MyProg if the last time you
    #	used java as type) will create a new file called MyProg.java:
    #
    #	public class MyProg
    #	{
    #		public static void main(String args[]){
    #		}
    #	}
    #
    #	examine and modify at will
    #
    #	author: Trucza Csaba ctrucza@cemc.soroscj.ro
    #
    #	this script may be full of errors
    #

    SE_HOME_DIR=~/.source-editor
    LAST_USED=$SE_HOME_DIR/last_used

    if [ -f $LAST_USED ] ; then
    	SE_DEFAULT_TYPE=`cat $LAST_USED`
    fi

    case $# in
    	0)
    	echo "no parameter"
    	if [ -z $SE_DEFAULT_TYPE ] ; then
    		SE_DEFAULT_TYPE=java
    	fi
    	FILE_TYPE=$SE_DEFAULT_TYPE
    	FILENAME=~/.source-editor/temp/temp.$FILE_TYPE
    	;;
    	1)
    	echo "filename"
    	if [ -z $SE_DEFAULT_TYPE ] ; then
    		SE_DEFAULT_TYPE=java
    	fi
    	FILE_TYPE=$SE_DEFAULT_TYPE
    	FILENAME=$1.$FILE_TYPE
    		;;
    	2)
    	echo "name and type"
    	FILE_TYPE=$2
    	FILENAME=$1.$FILE_TYPE
    	;;
    esac

    echo "FILE_TYPE="$FILE_TYPE
    echo "FILENAME="$FILENAME

    if [ -f $FILENAME ]; then
    	echo file exists
    else
    	build-template $FILE_TYPE $1
    	mv ~/.source-editor/templates/$FILE_TYPE.template $FILENAME
    fi
    echo $FILENAME
    echo $FILE_TYPE > $LAST_USED

    jstar -tab 4 $FILENAME
    ---------cut here---------------

The second script is a simple backup script, to back all the sources up and edit the tracking file.

    (file: backup)
    ---------cut here---------------
    #!/bin/sh
    #
    # 	kind of backup with kind of version control
    #	usage: backup
    #
    #	backs up the current directory (well not all of it, just your
    #	programs)
    #
    #	1. creates a dir named backup (or whatever)
    #	2. in this directory will be a tracking file, a plain text file
    #		in which you can write some comments every backup
    #	3. optionally in the file named filelist you can write the names of
    #	the files you want to back up
    #	4. examine and modify at will
    #
    #	author: Trucza Csaba ctrucza@cemc.soroscj.ro
    #
    #	this script may be full of errors
    #

    #
    #	where to back up
    #
    if [ -z $BACKUPDIR ] ; then
    	BACKUPDIR=backup
    fi

    if [ ! -d $BACKUPDIR ] ; then
    	mkdir $BACKUPDIR
    fi

    #
    #	last version backed up
    #

    LAST_FILE=$BACKUPDIR/last

    if [ -f $LAST_FILE ] ; then
    	VERSION=`cat <$LAST_FILE`
    else
    	VERSION=0
    fi
    let VERSION=$VERSION+1

    #
    #	prepare next backup directory
    #

    NEXT_DIR=$BACKUPDIR/ver.$VERSION

    mkdir $NEXT_DIR

    #
    #	get files to back up
    #

    LIST_FILE=$BACKUPDIR/filelist

    if [ -f $LIST_FILE ] ; then
    	cp `cat $LIST_FILE` $NEXT_DIR
    else
    #
    #	if no filelist found, backup C and Java files
    #	modify as you wish
    #
    	cp *.c $NEXT_DIR >/dev/null 2>&1
    	cp *.h $NEXT_DIR >/dev/null 2>&1
    	cp *.java $NEXT_DIR >/dev/null 2>&1
    fi

    #
    #	update last
    #

    echo $VERSION >$LAST_FILE

    #
    #	edit trackfile
    #

    TRACK=$BACKUPDIR/track

    echo >> $TRACK
    echo >> $TRACK
    echo "=====================================================================">> $TRACK
    date >> $TRACK
    echo "Version: "$VERSION >>$TRACK

    #
    #	here use your favorite editor :)
    #
    jstar $TRACK
    ---------cut here---------------

They should be self-explanatory. but, These scripts should not be used for design or development of nuclear, chemical, biological, weapons or missile technology, or any other places where humans can be hurt

### Syslog Thing

Date: Thu, 07 Aug 1997 15:00:29 -0700
From: Kent Friis dk5f@ehs.dk

In issue 20, I saw a 2c tip regarding syslog, Including changing the config file, and REBOOTING. Now wait a minute, I thought this was Linux. How can one get uptime's of 300+ days, if you need to reboot every time you change a config file.

The solution is simply to edit the config file, and kill -HUP (pid of syslogd).

You should NEVER need to reboot, except to install a new kernel.

Kent Friis.

### Sorta E-mail-to-Fax...Well to-Printer

Date: Fri, 8 Aug 1997 20:04:30 +0500 (PKT)
From: Tee Emm tm@super.net.pk

Hello,

I can bet that many of you readers will try out this tip atleast for once. Here we go:

I work at an ISP here in Pakistan with 4 more shift engineers. We have offices in three different locations and, although email and talk are used very frequently, we sometime require ABSOLUTELY IMMEDIATE responce from the other office. Emails remain unchecked and talk request are sometimes ignored because the other party might be busy doing something else on a talk-disabled terminal. Well, you cannot ignore a Panasonic Dotmatrix printer printing out messages in your control center!

One of my so-to-say boss talked of having a utility which will poll a POP3 mailbox every few seconds and printing out any mail that might be in the box. He, being a visual basic guru, started writing a windows based application that would do the required. I, being a die hard Linux creature, started thinking how I can do the same on my dear Linux box. Well, it took me a day to ponder on this issue and when I clicked, it was just a breeze! Sixteen key strokes and I was ready with my system. I yelled 'Windoz Suxs, Linux Rules'!

I edited the /etc/aliases file and keyed in the following line:

    urgent: 	"| lpr"

saved, the file and did a 'newaliases' and bingo! Any mail sent to urgent@super.net.pk was immediately printed on the screaming dot matrix printer. My boss was duly stunned!

(Note: You must have your 'lpr' command working before you can go ahead with this tip.)

Tariq Mustafa,

### Setting Xterm Title to Current Process

Date: Tue, 12 Aug 1997 01:09:02 -0500 (CDT)
From: Rob Mayoff mayoff@dqd.com

I saw this tip the Gazette: Hi, after searching (to no avail) for a way to display the currently executing process in the xterm on the xterm's title bar, I resorted to changing the source of bash2.0 to do what I wanted. from line 117 of eval.c in the source, add the lines marked with # (but don't include the #)

If you use ksh instead of bash, you can get the same effect without changing the source:

    typeset -A Keytable
    trap -- 'eval "${Keytable[${.sh.edchar}]}"' KEYBD
    [[ "$TERM" == xterm ]] && \
    Keytable[$'\r']=$'[[ -n ${.sh.edtext} ]] && print -n "\E]2;${.sh.edtext}\a"'

You can download ksh (the POSIX-compliant Korn shell) for free from http://www.research.att.com/orgs/ssr/book/reuse

### CVS

Date: Thu, 14 Aug 1997 11:08:27 -0400
From: Paul Rensing paulr@dragonsys.com

Mario Storti wrote:

Using shar + RCS to Backup Set of Source Files

Hi, RCS (see rcs(1)) is a very useful tool that allows to store versions of a file by storing only the differences between successive versions. In this way I can make a large amounts of backups of my source files but with a negligible amount of storage. I use it all the time, even for TeX files!! However, when you are working with a set of source files (*.c, shell or Perl scripts, I work mainly with Fortran .f and Octave *.m files) what I want is to make backups of the whole set of files in such a way that you can recover the state of the whole package at a given time. I know that there is a script called rcsfreeze around, but I know that it has problems, for instance if you rename, delete or create new files, it is not guaranteed to recover the same state of the whole set.

I think a good way to handle this is by "upgrading" to CVS. CVS is a version control system built on top of RCS and was designed specifically to handle version control of large trees of files (the company who wrote it was a Sun VAR and handled the > 1000 files which they regularly received from Sun).

Once you have the project set up, you could simply do "cvs commit" from the top directory of a project, and CVS will check in all the changes to all the controlled files in the tree. If you are using this for "backup", you would only need to keep a copy of the CVS "repository".

Paul Rensing

Published in Linux Gazette Issue 21, September 1997

##### This page maintained by the Editor of Linux Gazette, gazette@ssc.com
Copyright © 1997 Specialized Systems Consultants, Inc.