Jeremy
Jeremy

Reputation: 15

Dynamic variable created in function not available in future calls

I have a script that is (supposed to be) assigning a dynamic variable name (s1, s2, s3, ...) to a directory path:

savedir() {
    declare -i n=1
    sn=s$n
    while test "${!sn}" != ""; do
        n=$n+1
        sn=s$n
    done
    declare $sn=$PWD
    echo "SAVED ($sn): ${!sn}"
}

The idea is that the user is in a directory they'd like to recall later on and can save it to a shell variable by typing 'savedir'. It -does- in fact write out the echo statement successfully: if I'm in the directory /home/mrjones and type 'savedir', the script returns: SAVED (s1): /home/mrjones

...and I can further type:

echo $sn

and the script returns: s1

...but typing either...

> echo $s1

...or

echo ${!sn}

...both return nothing (empty strings). What I want, in case it's not obvious, is this:

echo $s1

/home/mrjones

Any help is greatly appreciated! [apologies for the formatting...]

Upvotes: 0

Views: 32

Answers (2)

chepner
chepner

Reputation: 532518

Use an array instead.

savedir() {
    s+=("$PWD")
    echo "SAVED (s[$((${#s[@]}-1))]): ${s[${#s[@]}-1]}"
}

Upvotes: 1

Eric Renouf
Eric Renouf

Reputation: 14520

To set a variable using a name stored in another variable I use printf -v, in this example:

printf -v "$sn" '%s' "$PWD"

declare here is creating a variable local to the function, which doesn't seem to be what you want. Quoting from help declare:

When used in a function, declare makes NAMEs local, as with the local command. The -g option suppresses this behavior.

so you can either try the -g or with the printf

Upvotes: 1

Related Questions