How to Parse A Shell Command Twice

Let me introduce shell variables $0 ... $9, ${10}.., $# before I get to parsing shell command again using eval.

Shell assigns the parameters that you pass though a command to its built in variables $1, $2... $9, ${10}...
The number of arguments passed are stored in $#.

Run this command:
set a b c d e f g
The command will set a to $1, b to $2, c to $3 ... g to $7

If I run the following command, the output will be c
echo $3

Now let's look at the following example:


echo $$
9609

$$ returns the PID of the process


echo $$$
9609$

In the above example $$ is parsed as pre-defined variable $$ and the additional $ is appended to the output. What if I want to print $ followed by PID pf the process? I can do that by preceding that $ with \
\ tells the shell not to interpret the next character's special meaning.


echo \$$$
$9609

Now let's get to parsing the command twice. If I want to print the last argument passed, how do I do it?
In the following example g is the last argument passed
set a b c d e f g

As I know that 7 arguments are passed, echo $7 will print the last variable. What if the last variables is not known?
echo \${$#} will print $7 as output. So I need to re-evaluate the output to print the last argument. This can be done using eval command

eval echo \${$#}

The above command will parse \${$#} to $7 in our example and parse the command again as echo $7 to print g as output. There are other ways of printing the last argument (example using a loop), but this one is my favorite.


Comments

Popular posts from this blog

OS/DB Migration - CMD. STR, TOC, EXT, R3load, DDLDBS.TPL and more

Fixing Inconsistent Table - Table activation fails due to inconsistency between DD and DB

301 Redirect Using SAP Web Dispatcher