Tuesday, April 6, 2010

Dynamic korn shell (ksh) variable assignments

This might seem like a strange thing to want to do, but imagine you read in a list of user names, and for each one you want to store some info, such as the assigned shell.

Now, you could just put user names in one array, and the info in another array, and rely on the fact that both arrays will have the same index order.

But, you can also use "eval":

$ name=bob
$ data=/bin/bash
$ eval "$name=$data"

And to "de-reference" your dynamic variable:

$ eval "echo \$$name"
/bin/bash

This also works:

$ eval echo "$"$name
/bin/bash

0 comments: