Bash create a variable and then assign it a value

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

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

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

 dir_1_0=directory_one 

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

 $(temp)=another_directory 

coincides with

 dir_2_4=another_directory 

so that I can call, for example

 cd $(temp) 

which will move me to different directories when I need

+4
source share
3 answers

I think you want to use eval . For instance:

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

So what you can do is something like

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

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 

sh script output:

 /Users/jleffler/tmp/soq /tmp 

Converted to 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 names recorded are the names of the remaining directory, not the one to which you came.

+3
source

A safe way to do this is to use indirect, associative arrays (Bash 4), functions, or declare :

Use declare :

 declare $temp=$name_of_directory 

Using Indirection:

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

Note the safety implications of eval .

+1
source

Source: https://habr.com/ru/post/1338204/


All Articles