我想将环境变量存储在 bash 数组中,然后在对所有环境变量执行相同操作(取消设置、导出等)的情况下使用它们。例如,如果我想打印数组中的所有环境变量:
envVar1="firstVar"
envVar2="secondVar"
envVar3="thirdVar"
envVars=(envVar1 envVar2 envVar3)
for currentEnvVar in "${envVars[@]}"
do
# print env var name and value
printf "Initial Value: %s = %s\n" "${currentEnvVar}" "${currentEnvVar}"
# unset env var
printf "Unsetting %s\n" "${currentEnvVar}"
unset "${currentEnvVar}"
# print env var name and value
printf "Unset Variable (nothing should be to right of '=') %s = %s\n\n" "${currentEnvVar}" "${currentEnvVar}"
# set env var
printf "Setting %s\n" "${currentEnvVar}"
export "${currentEnvVar}"="${currentEnvVar}""_new"
# print env var name and new value...
printf "New Value %s = %s\n\n" "${currentEnvVar}" "${currentEnvVar}"
done
我不确定的是如何存储变量envVars
以及如何在循环中使用它们。
我的目标是上述循环的输出为:
Initial Value: envVar1 = firstVar
Unsetting envVar1
Unset Variable (nothing should be to right of '=') envVar1 =
Setting envVar1
New Value envVar1 = firstVar_new
Initial Value: envVar2 = secondVar
Unsetting envVar2
Unset Variable (nothing should be to right of '=') envVar2 =
Setting envVar2
New Value envVar2 = secondVar_new
Initial Value: envVar3 = thirdVar
Unsetting envVar3
Unset Variable (nothing should be to right of '=') envVar3 =
Setting envVar3
New Value envVar3 = thirdVar_new
但我得到的是这样的:
Initial Value: envVar1 = envVar1
Unsetting envVar1
Unset Variable (nothing should be to right of '=') envVar1 = envVar1
Setting envVar1
New Value envVar1 = envVar1
Initial Value: envVar2 = envVar2
Unsetting envVar2
Unset Variable (nothing should be to right of '=') envVar2 = envVar2
Setting envVar2
New Value envVar2 = envVar2
Initial Value: envVar3 = envVar3
Unsetting envVar3
Unset Variable (nothing should be to right of '=') envVar3 = envVar3
Setting envVar3
New Value envVar3 = envVar3
这可能吗?如何设置环境变量名称数组,然后使用或修改它们的值?
答案1
您似乎正在尝试做的事情有几个不同的部分。
对于unset
名称在另一个变量中的变量,可以使用-v
so
unset -v "$currentEnvVar"
对于那部分。看这里
要分配给变量,您可以使用printf
喜欢
printf -v "$currentEnvVar" %s 'new value'
要打印该值,您可以使用间接引用喜欢
printf 'The value is %s\n' "${!currentEnvVar}"
在大括号扩展中,如果第一个字符是,!
则其余字符被视为包含您要实际使用的变量名称的变量名称。
您还可以考虑使用关联数组相反,如果它适合您的需求:
declare -A envVarsByName
envVarsByName[$currentEnvVar]='new value'
printf 'New val: %s\n' "${envVarsByName[$currentEnvVar]]}"