LDP/LDP/guide/docbook/abs-guide/echo-params.sh

40 lines
1.2 KiB
Bash
Raw Normal View History

2006-12-20 21:12:30 +00:00
#!/bin/bash
# echo-params.sh
2008-11-23 22:43:47 +00:00
# Call this script with a few command-line parameters.
2006-12-20 21:12:30 +00:00
# For example:
# sh echo-params.sh first second third fourth fifth
params=$# # Number of command-line parameters.
param=1 # Start at first command-line param.
while [ "$param" -le "$params" ]
do
2008-11-23 22:43:47 +00:00
echo -n "Command-line parameter "
2006-12-20 21:12:30 +00:00
echo -n \$$param # Gives only the *name* of variable.
# ^^^ # $1, $2, $3, etc.
# Why?
# \$ escapes the first "$"
#+ so it echoes literally,
#+ and $param dereferences "$param" . . .
#+ . . . as expected.
echo -n " = "
eval echo \$$param # Gives the *value* of variable.
# ^^^^ ^^^ # The "eval" forces the *evaluation*
#+ of \$$
#+ as an indirect variable reference.
(( param ++ )) # On to the next.
done
exit $?
# =================================================
$ sh echo-params.sh first second third fourth fifth
2008-11-23 22:43:47 +00:00
Command-line parameter $1 = first
Command-line parameter $2 = second
Command-line parameter $3 = third
Command-line parameter $4 = fourth
Command-line parameter $5 = fifth