Finding the last arg

Martin Weitzel martin at mwtech.UUCP
Wed Jan 2 21:37:29 AEST 1991


In article <1990Dec27.060903.1604 at onion.pdx.com> jeff at onion.pdx.com (Jeff Beadles) writes:
>In <18476 at shlump.nac.dec.com> lan_csse at netrix.nac.dec.com writes:
>>The problem is that I can't figure out any Bourne-shell expression that
>>gives the last argument.
>...
>>Any ideas?
>
>Well, there's nothing that I am aware of in /bin/sh that will ALWAYS allow
>this to work.  The problem is that if you have more than 9 arguements, you
>have to shift them off to get to what you want.

Not really. I have waited some time, but as Chris Torek seems to be in
vacation I'll bite the bullet this time :-) [%].

What ALLWAYS works in the Bourne-Shell is this:

	for last do :; done

Explanation: The for loop loops over all arguments of the current procedure,
if you leave out the `in'-clause. Every argument is put into the variable
you name after `for'. This leaves the last argument in last when the loop is
through.

You can also access the second last (third last, etc) argument if you
extend this trick a little:

	for i
	do
		last3=$last2
		last2=$last
		last=$i
	done

And please DON'T use `for i in $*' instead of leaving the `in'-clause out!
It's not the same - despite some UNIX books claim so!! (For the nit-pickers:
`for i' is the same as `for i in ${1+"$@"}' i.e. you will never run into
problems if there are no arguments or some arguments have embedded blanks.)

%: Shouldn't this be in the FAQ-list or is it? (I've no recent copy available)
-- 
Martin Weitzel, email: martin at mwtech.UUCP, voice: 49-(0)6151-6 56 83



More information about the Comp.unix.shell mailing list