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.

4

2 回答 2

8

${!var}Bash 版本 2为动态创建的变量名称(又名“间接引用”)引入了更直观的表示法......

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

有关详细信息和示例,请参阅http://tldp.org/LDP/abs/html/bashver2.html#EX78

有关使用更知名eval var1=\$$var2技术的详细信息和示例,请参阅http://tldp.org/LDP/abs/html/ivr.html

于 2013-05-06T05:02:42.627 回答
6

Export 将变量导出到当前的 shell 上下文中。通过使用 bash 运行脚本,它会在该 shell 的上下文中设置。您需要获取文件以使其在当前 shell 上下文中运行。

source <filename>.sh

只是为了显示子外壳和源之间的区别:

[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
于 2013-01-28T17:00:11.700 回答