Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export variable from within while loop

Tags:

linux

bash

shell

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
like image 999
Sunil Sharma Avatar asked Sep 18 '25 20:09

Sunil Sharma


1 Answers

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

like image 72
Inian Avatar answered Sep 21 '25 12:09

Inian