Variable substitition

Maarten Litmaath maart at cs.vu.nl
Sat Dec 1 07:09:31 AEST 1990


In article <1990Nov30.092424 at cs.utwente.nl>,
	stadt at cs.utwente.nl (Richard van de Stadt) writes:
)Is there some sort of variable substitution possible in a shell script
)to get the value of the last argument supplied to the script? I don't
)mean shifting the arguments until one is left. I'd like to know if something 
)like awk's $NF, in which NF means the number of fields, and $NF means the 
)value of the last field, is possible. ${$#} results in an error message.

# How to get the last argument of a shell script reliably.
# If you are sure there are fewer than 10 arguments, you can use this:
#
#	eval echo \"\$$#\"
#
# Instead of ``echo "$foo"'' you could use the portable echo hack:
#
#	expr "$foo" : '\(.*\)'
#
# Alternatively:
#
#	cat << EOF
#	$foo
#	EOF

set a b c d e f g h i j k l m -n	# for example

case $# in
0)
	last=
	;;
*)
	last=`
		n=$#
		set 0 ${1+"$@"}
		shift $n
		echo -n "$1"
	`
esac

echo "last=|$last|"
--
"Please DON'T BREAK THE CHAIN!  Terry Wood broke the chain and ended up
writing COBOL PROGRAMS.  Three days later, he found his Blue Star Tatoo
Letter, made 20 copies and mailed them out.  He found a good job writing
compilers."  --  tjw at unix.cis.pitt.edu (Terry J. Wood)



More information about the Comp.unix.questions mailing list