Finding the last arg
John Chambers
jc at minya.UUCP
Sun Jan 6 02:56:45 AEST 1991
> What ALLWAYS works in the Bourne-Shell is this:
>
> for last do :; done
Wow! A one-liner that works for more than 9 args! Of course, there's
the question as to whether this loop is actually faster than starting
a subprocess that just does puts(argv[artc-1]), but at least there's
a way to do it that is portable.
That comment isn't worth wasting the bandwidth, of course; my motive
for this followup is a bit of bizarreness that I discovered while
testing this command. The usual format of a for loop is 3 lines:
for last
do :
done
Usually when I want to collapse such vertical code into a horizontal
format, I follow the rule "Replace the newlines with semicolons", and
it works. For instance,
if [ <test> ]
then <stuff>
else <stuff>
fi
reduces to
if [ <test> ];then <stuff>;else <stuff>;fi
which I can do in vi via a series of "Jr;" commands. With the above
for-loop, this gives
for last;do :;done
which doesn't work. The shell gives a syntax error, complaining about
an unexpected ';' in the line. Myself, I found this to be a somewhat
unexpected error message. It appears my simple-minded algorithm for
condensing code doesn't work in this case.
So what's going on here? What the @#$^&#( is the shell's syntax that
makes the semicolon not only unneeded, but illegal in this case?
One of the real hassles I keep finding with /bin/sh (and /bin/csh is
even worse ;-) is that the actual syntax regarding things like white
space, newlines, and semicolons seems to be a secret. It often takes
a lot of experimenting to find a way to get these syntax characters
right. Is there any actual documentation on sh's syntax? Is it truly
as ad-hoc as the above example implies? Is there perhaps some logical
structure underlying it all that would explain why
for last do :; done
and
for last
do :
done
both work but
for last;do :;done
doesn't?
--
Zippy-Says: Imagine ... a world without clothing folds, chiaroscuro, or marital difficulties ...
Home: 1-617-484-6393 Work: 1-508-952-3274
Uucp: ...!{harvard.edu,ima.com,eddie.mit.edu,ora.com}!minya!jc (John Chambers)
Uucp-map: minya adelie(DEAD)
More information about the Comp.unix.shell
mailing list