5

I want to create a variable with its name partly dynamic and export it from my bash shell script. I have been trying to do it the following way. No success though. Please tell me where I am wrong.

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

execution command

bash <filename>.sh

I am hoping the script would create an environmental variable like METASTORE_JDBC_DRIVER_8769 and I should be able to use that out of the script but when I do echo $METASTORE_JDBC_DRIVER_8769 outside the script, doesn't give me anything. Any suggestions/ideas are welcomed.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Nitin
  • 103
  • 1
  • 1
  • 6
  • Possible duplicate of [How can I generate new variable names on the fly in a shell script?](http://stackoverflow.com/questions/10820343/how-can-i-generate-new-variable-names-on-the-fly-in-a-shell-script) – Benjamin W. Oct 06 '15 at 16:50

2 Answers2

9

Bash version 2 introduced the much more intuitive notation ${!var} for dynamically created variable names (a.k.a "indirect referencing")...

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

For details and examples, see http://tldp.org/LDP/abs/html/bashver2.html#EX78

For details and examples using the more well-known eval var1=\$$var2 technique, see http://tldp.org/LDP/abs/html/ivr.html

DocSalvager
  • 2,156
  • 1
  • 21
  • 28
  • 1
    What you say is accurate as far as it goes, but it would be better if your examples ended up addressing the problem shown in the question (as well as, or instead of, the example you devised). – Jonathan Leffler May 06 '13 at 06:39
  • And that's why Erik's answer was accepted over mine. Point taken for the future. Thanks. – DocSalvager Apr 25 '14 at 21:56
7

Export exports variables into the current shell context. By running your script with bash it gets set in that shell's context. You need to source the file to have it run in the current shell context.

source <filename>.sh

Just to show the difference between a 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
Erik Nedwidek
  • 6,134
  • 1
  • 25
  • 25