Sunil Sharma
Sunil Sharma

Reputation: 59

Export variable from within while loop

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

Upvotes: 4

Views: 12649

Answers (4)

yosefrow
yosefrow

Reputation: 2268

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"

see http://wiki.bash-hackers.org/syntax/quoting

Upvotes: 0

user3089519
user3089519

Reputation:

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.

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60068

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

Upvotes: 0

Inian
Inian

Reputation: 85590

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

Upvotes: 3

Related Questions