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
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
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.
$IFS) and parse it later with real_list=($seperated_list) You can then retrieve values by first_var=${real_list[0]}export some_list=("${thelist[@]}") The main precaution to take is that if your IFS field seperator is a space for example, you may get incorrect data when parsing back into a list.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"
$ithe value you expect it to be? Perhaps you shouldechoit to make sure.