I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.
Any suggestion would be great help
var="ahs tcs amq tos"
for i in ${var}
do
${i}_log="/var/tmp/pmp_${i}_log"
#export ${i}_log
done
The idea is right, just use the declare
variable to create variables on the fly. Also avoid using un-quoted variable expansion( for i in ${var}
) for looping. Use a proper array syntax as
var=("ahs" "tcs" "amq" "tos")
for i in "${var[@]}"; do
declare ${i}_log="/var/tmp/pmp_${i}_log"
export "${i}_log"
done
As a side note for good practice, always specify the interpreter to run your script. It could be #!/bin/bash
or #!/bin/sh
or best do it by #!/usr/bin/env bash
An alternative could be to use a single exported associative array instead of multiple variables:
EDIT: oops, this won't work since arrays can't be exported. :\\
var="ahs tcs amq tos"
declare -A logs
for i in ${var}
do
logs[$i]="/var/tmp/pmp_${i}_log"
done
echo ${logs[@]}
#### export logs
Also see Inian's answer for better practices for looping and arrays.
This works on dash and bash (as long as the i's and the path to interpolate them into are reasonable):
#!/bin/sh
var="a b c d"
for i in $var
do
export "${i}_log=/var/tmp/pmp_${i}_log"
#test
sh -c "echo \$${i}_log"
done
This can be done in one line without a loop
printf '%s\n' {ahs,tcs,amq,tos} | xargs -I {} bash -c 'export {}_log="/var/tmp/pmp_{}_log"; echo {}_log=${{}_log}'
or with a loop
#!/bin/bash
for i in {ahs,tcs,amq,tos}; do
#export
export "${i}_log=/var/tmp/pmp_${i}_log";
#test
bash -c 'echo '"${i}_log"'='"\$${i}_log"; done
done
The reason ${i}_log="/var/tmp/pmp_${i}_log"
failed is because ${i}_log
is unquoted and the syntax for exporting is export somevar=somedefintion
. In order to dynamically generate the variable name, surround the statement in quotes so that it gets interpolated. ie. export "${dynamic}_var=${dynamic}_definition"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.