KSH 中的动态环境变量

Dynamic Environment Variable in KSH

我必须在 KSH 中编写一个定义和使用动态环境变量的脚本。

它应该读取以下格式的文件

 DEV  server_name  DEV_Server
 QA   server_name  QA_Server
 PROD server_name  PROD_Server

所以如果要在DEV中执行脚本,会这样调用:

     Invocation            Value of server_name
 **script.sh DEV**               DEV_Server
 **script.sh QA**                QA_Server

关于如何在 KSH 中实现动态变量的任何线索?

使用 ksh93v 或更新版本,您可以使用 typeset -n 使名称引用不同的、动态定义的变量:

# recommended syntax for ksh but not bash; in ksh, makes all variables local by default
# does not have that effect in bash, and is best avoided there.
function indirect_assign { nameref _dest=; _dest=; }

while read -r env_name var_name var_value; do
  [[ $env_name = "" ]] || continue
  indirect_assign "$var_name" "$var_value"
  export "$var_name"
done

请注意,需要获取此代码(或作为函数体调用)才能对调用产生任何影响 shell。