Technical article 105800

My shell scripts using awk give unexpected results in SCO OpenServer 5.0.4.

OpenServer 5.0.4

Written · Last revised

Problem

Shell scripts using awk, which have worked correctly in versions
of SCO UNIX prior to SCO OpenServer 5.0.4, are now producing
different results.  In particular, the first value returned is
sometimes blank rather than the expected value. This can be
demonstrated from the command line as follows:
%cat /etc/passwd | grep root | awk '{ FS=":" ; print $5 }'

This has always returned Superuser in previous revisions, but now it returns a blank line.

Cause

The problem is now occurring because of modifications made to awk
in order to make it XPG4 compliant.  In the example above, the
change of FS is in the "action" which is executed after the first
record (line) is read. This becomes clearer if the example above
is modified to return the names of all users in the password file
as follows:
%cat /etc/passwd | awk '{ FS=":" ; print $5 }'

All names are printed except for the first entry which appears blank.

Solution

The awk string should be rewritten to ensure that the field separator is defined before the first record is processed. This can be done by either using the -F command line option or making use of the BEGIN action. For the example above, this can be rewritten as follows:

%cat /etc/passwd | awk -F: '{ print $5}'
or:
%cat /etc/passwd | awk 'BEGIN {FS = ":"} {print $5}'

In both of these examples, all user names are returned.

From the Xinuos technical article database, record 105800. Reproduced with permission. The original is at www.sco.com/ta/105800, which is reachable but blocked from search engines. Xinuos marks this article against a retired product line. That refers to the product’s lifecycle, not to whether the advice still works — plenty of it still applies to running systems.

Next step

Need this fixed rather than explained?

Tell us the release, what the system runs and what it is doing. We will reply by email with what we would do next.

  • You deal with the people who do the work
  • No obligation, and no upgrade required before we will help
  • We tell you plainly if something is not worth doing

Send an enquiry

We reply by email. If a server is down, say so in the first line. You can also write to help@scoexpert.com.