[SGVLUG] shell script & nawk exposure

Bryan D Howard bryan at jetcafe.org
Wed Feb 22 12:59:57 PST 2006


Don Gibbs <donald.e.gibbs at jpl.nasa.gov> writes:
<snip>
>   NAME=`echo ls -lrt *_data | nawk '{print $NF}'`
>   echo $NAME

Don,

I don't think this is doing what you think it is.  The above does not
run ls(1) at all.  It's just echoing those characters prior to all the
filenames which are a result of the shell expanding the wildcard.  You
might as well write it this way:

  NAME=`echo *_data | nawk '{print $NF}'`
  echo $NAME

Given this, it should not be surprising that the echo separates the
names with spaces rather than newlines, since that's what the shell is
defined to do.  If you want to keep it all within the shell, you could
do this:

  NAME=`set *_data ; eval echo '$'{$#}`

Please note: Each of the above will only do what you said you wanted
assuming that the shell lists the files in a particular order.  To my
knowledge, it lists them in the order they appear *in the directory*.
This means that if you ever delete files and then add new ones, it may
reuse slots and mess up your order assumptions.

What I recommend doing instead, is:

  NAME=`ls -t *_data | head -1`

I also find this version clearer and there's a lot to be said for
readability.  Both for myself looking at it again much later, and for
anyone else looking at it.

{Bryan}
-- 
Bryan D Howard
<bryan at alumni.caltech.edu>


More information about the SGVLUG mailing list