Finding the last arg

CSSE LAN Test Account lan_csse at netrix.nac.dec.com
Thu Dec 27 03:19:03 AEST 1990


Well, it should have been easy, but everything I've tried has failed, so
I'll go to the experts... (;-)

What I've been trying to do is write a script whose semantics are sort of
like the cp/mv/ln commands, in that the last argument is special.  If it
is a directory, I want to do something different that amounts to appending
character strings to its name to give file name[s] within the directory;
if it is an ordinary file, I just want to use its name.

The problem is that I can't figure out any Bourne-shell expression that
gives the last argument.  In C-shell, it's easy (argv[$#]).  But I need
to write Bourne shell scripts.  In fact, they need to be BSD bourne shell
scripts rather that ATT Bourne shell scripts.  The difference is probably
significant here, because of the differences in the way these two Bourne
shells handle variables.  Actually, it'd be really nice to find a solution
that is portable, but that may be just a dream.

The obvious thing to try is some sort of expression combining $# with ${},
e.g. ${$#}.  This gets a syntax error.  The simpler $$# is valid, but it
just gives the process id followed by a '#', not even close.  I've also 
tried assigning $# to a variable and using that, but all I've managed to
get is the number of the last arg, not its value.

At the moment I've kludged the job by writing a program lastfld.c that just
prints argv[argc-1].  But it seems incredibly stupid to have to pass all
the args to a subprocess which throws away all but the last one.  I mean,
the shell knows which arg is which; why go to the expense of starting up
a subprocess to learn something that the parent already knows?

The pseudo-code I'd like to use is:
	if [ -d last-command-line-arg ]
	then
		...
	fi
Any ideas?



More information about the Comp.unix.shell mailing list