Martin Nielsen
Martin Nielsen

Reputation: 2049

ksh: Defining a parameter name with another parameter's value

I have a ksh script that reads a profile script with a number of sessions defined. Each session defines its own parameters as such:

SESSION_ONE_USER=...
SESSION_ONE_PWD=...
SESSION_TWO_USER=...
...

The script gets the SESSION parameter from the command line, but I simply set it for the example.

I want to let the SESSION parameter value define part of another parameter name, that I need the value from, like:

SESSION="SESSION_ONE"
USER=${${SESSION}_USER}
PASS=${${SESSION}_PWD}

That gives me a compile error. I also tried

GET_USER_PARAM(){
    echo ${SESSION}_USER
}
echo $`GET_USER_PARAM`

But that returns $SESSION_ONE_USER

I want it to return the value of the parameter SESSION_ONE_USER instead. Does anyone have any solutions?

Upvotes: 0

Views: 762

Answers (4)

Henk Langeveld
Henk Langeveld

Reputation: 8456

If this is ksh, then this is a job for nameref

alias nameref='typeset -n'

Example Solution

function session_parameters { set -u
    typeset session=${1:?session name}
    nameref user=SESSION_${session}_USER
    nameref pass=SESSION_${session}_PASS
    print session=$session user=$user pass=$pass
}
SESSION_ONE_USER="User1"
SESSION_ONE_PASS="Pass1"
SESSION_TWO_USER="User2"
SESSION_TWO_PASS="Pass2"
for s in ONE TWO THREE; do
    session_parameters $s
done

Sample output

session=ONE user=User1 pass=Pass1
session=TWO user=User2 pass=Pass2
test_session_parameters[12]: session_parameters: line 5:
SESSION_THREE_USER: parameter not set

Note the usage of set -u to force the error message on line 3.


nameref usage: (from the builtin help text)

NAME

typeset - declare or display variables with attributes

SYNOPSIS

typeset [ options ] [name[=value]...]

-n Name reference.

The value is the name of a variable that name references. name cannot contain a ... Cannot be use with any other options.

Upvotes: 1

Ziffusion
Ziffusion

Reputation: 8933

Try this:

SESSION="SESSION_ONE"
SESSION_ONE_USER="foo"
SESSION_ONE_PWD="bar"

SESSION_USER=${SESSION}_USER
SESSION_PWD=${SESSION}_PWD

USER=${!SESSION_USER}
PASS=${!SESSION_PWD}

echo $USER
echo $PASS

The "!" does a level of indirection. See Shell Parameter Expansion.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247082

Don't monkey with variable names, use associative arrays instead

typeset -A users
typeset -A pwd

session=SESSION_ONE
users[$session]=joe
pwd[$session]=secret

for key in "${!users[@]}"; do
    echo "user for session $key is ${users[$key]}"
    echo "pwd  for session $key is ${pwd[$key]}"
done

Upvotes: 1

twalberg
twalberg

Reputation: 62469

This is what eval is for:

SESSION=SESSION_ONE
eval echo \$${SESSION}_USER

should display the value of $SESSION_ONE_USER.

Upvotes: 1

Related Questions