Export variable with dynamically generated name in bash shell script

I want to create a variable with its name, partially dynamic, and export it from my bash shell script. I tried to do it like this. However, there is no success. Please tell me where I am going wrong.

#!/bin/bash
CURRENT_PROCESS_ID=$$
var=METASTORE_JDBC_DRIVER_$CURRENT_PROCESS_ID
echo $var
export $var='1'

      

execute command

bash <filename>.sh

      

I hope the script will create an environmental variable of type METASTORE_JDBC_DRIVER_8769

and I will have to use it from within the script, but when I do it echo $METASTORE_JDBC_DRIVER_8769

outside the script it gives me nothing. Any suggestions / ideas are greatly appreciated.

+3


source to share


2 answers


Export exports variables to the current shell context. By running the script with bash, it will be installed in that shell context. You need to specify the file to execute in the current shell context.

source <filename>.sh

      



Just to show the difference between sub-shell and source:

[nedwidek@yule ~]# bash test.sh
METASTORE_JDBC_DRIVER_8422
[nedwidek@yule ~]# env |grep META
[nedwidek@yule ~]# source test.sh
METASTORE_JDBC_DRIVER_8143
[nedwidek@yule ~]# env |grep META
METASTORE_JDBC_DRIVER_8143=1

      

+5


source


Bash version 2 introduced a much more intuitive notation ${!var}

for dynamically generated variable names (aka "indirections") ...

a=letter_of_alphabet
letter_of_alphabet=z

echo "a = $a"           # Direct reference.

echo "Now a = ${!a}"    # Indirect reference.  (a = z)
#  The ${!variable} notation is more intuitive than the old
#+ eval var1=\$$var2

      



See http://tldp.org/LDP/abs/html/bashver2.html#EX78 for details and examples

For more details and examples using a better known method eval var1=\$$var2

see http://tldp.org/LDP/abs/html/ivr.html

+8


source







All Articles