Unix Power ToolsUnix Power ToolsSearch this book

36.9. Finding the Last Command-Line Argument

Do you need to pick up the last parameter $1, $2 ... from the parameter list on the command line? It looks like eval \$$# would do it:

eval Section 27.8

$ set foo bar baz
$ eval echo \$$#
baz

except for a small problem with sh argument syntax:

$ set m n o p q r s t u v w x
$ echo $11
m1

$11 means ${1}1, not ${11}. Trying ${11} directly gives bad substitution. (More recent shells, such as bash, do support the ${11} syntax, however, to arbitrary lengths. Our copy of bash, for example, allowed at least 10240 command line arguments to set with recall of the last via ${10240}). Your mileage may vary.

The only reliable way to get at the last parameter in the Bourne shell is to use something like this:

for i do last="$i"; done

The for loop assigns each parameter to the shell variable named last; after the loop ends, $last will have the last parameter. Also, note that you won't need this trick on all sh-like shells. The Korn shell, zsh, and bash understand ${11}.

-- CT



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.