mike
mike

Reputation: 3519

Bash create variable then assign value to it

For this problem I have two values, curdir and curlevel, which change throughout my script. I want to know if it's possible to create a variable and then use that value as the name for another value. For example

temp="dir_${curdir}_${curlevel}"
$temp=$name_of_directory  **<----Is there a legitimate way to do this?**

so if initially curdir=1 and curlevel=0 then $(temp)=directory_one is equal to

dir_1_0=directory_one

then later if curdir=2 and curlevel=4, I can reset temp and then have

$(temp)=another_directory

is the same as

dir_2_4=another_directory

so I could make a call such as

cd $(temp)

which will move me to different directories when I need to

Upvotes: 5

Views: 7365

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 359875

The secure way to do this is to use indirection, associative arrays (Bash 4), functions or declare:

Use declare:

declare $temp=$name_of_directory

Use indirection:

bar=42
foo=bar
echo ${!foo}
IFS= read -r $foo <<< 101
echo ${!foo}

Please take note of the security implications of eval.

Upvotes: 1

Brian
Brian

Reputation: 2551

I think what you want is to use eval. Like so:

 $ foo=bar
 $ bar=baz
 $ eval qux=\$$foo
 $ echo $qux
 baz

So what you could do is something like

eval temp=\$$"dir_${curdir}_${curlevel}"
cd $temp

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

The trick for this is to use eval - several times.

curdir=1
curlevel=0
temp='dir_${curdir}_${curlevel}'      # Note single quotes!
x=$(eval echo $temp)
eval $x=$PWD
cd /tmp
curdir=2
curlevel=4
x=$(eval echo $temp)
eval $x=$PWD

echo $dir_1_0
echo $dir_2_4

The output of sh -x script:

+ curdir=1
+ curlevel=0
+ temp='dir_${curdir}_${curlevel}'
++ eval echo 'dir_${curdir}_${curlevel}'
+++ echo dir_1_0
+ x=dir_1_0
+ eval dir_1_0=/Users/jleffler/tmp/soq
++ dir_1_0=/Users/jleffler/tmp/soq
+ cd /tmp
+ curdir=2
+ curlevel=4
++ eval echo 'dir_${curdir}_${curlevel}'
+++ echo dir_2_4
+ x=dir_2_4
+ eval dir_2_4=/tmp
++ dir_2_4=/tmp
+ echo /Users/jleffler/tmp/soq
/Users/jleffler/tmp/soq
+ echo /tmp
/tmp

The output of sh script:

/Users/jleffler/tmp/soq
/tmp

Converted to a function:

change_dir()
{
    temp='dir_${curdir}_${curlevel}'      # Note single quotes!
    x=$(eval echo $temp)
    eval $x=$PWD
    cd $1
}

curdir=1
curlevel=0
change_dir /tmp

curdir=2
curlevel=4
change_dir $HOME

echo $dir_1_0
echo $dir_2_4
pwd

Output:

/Users/jleffler/tmp/soq
/tmp
/Users/jleffler

The recorded names are the names of the directory being left, not the one you arrive at.

Upvotes: 3

Related Questions