Results 1 to 4 of 4
I have noticed a strange issue with a bash script I am writing. If I do a declare -x in a loop inside of a function the variable is cleared ...
- 06-06-2008 #1Just Joined!
- Join Date
- Sep 2006
- Posts
- 4
bash declare -x strangeness
I have noticed a strange issue with a bash script I am writing. If I do a declare -x in a loop inside of a function the variable is cleared the first time through the loop. Each subsequent iteration it works as expected. If run the same loop outside of a function it works fine. Also if I use export instead of declare -x it works. Anyone know why this is? I am probably just not understanding something about variable scoping. I am doing the declare so I can export the variable to a perl one liner inside the loop
for ex:
declare -x blah
perl -wle 'print "$ENV{blah}"
Here is a test script showing the problem
Code:#!/bin/bash function animals { for animal in cat dog chicken rabbit; do echo "---------------------" echo "Before export = $animal" declare -x animal echo "After export = $animal" echo "---------------------" done } animalsCode:--------------------- Before export = cat After export = --------------------- --------------------- Before export = dog After export = dog --------------------- --------------------- Before export = chicken After export = chicken --------------------- --------------------- Before export = rabbit After export = rabbit ---------------------
- 06-06-2008 #2Just Joined!
- Join Date
- Sep 2006
- Posts
- 4
Here is a simpler example without the loop showing the same issue:
ResultsCode:function animals { echo "Inside Function" animal=cat echo "---------------------" echo "Before export = $animal" declare -x animal echo "After export = $animal" echo "---------------------" } animals echo "Outside Function" animal=zebra echo "---------------------" echo "Before export = $animal" declare -x animal echo "After export = $animal" echo "---------------------"
Code:Inside Function --------------------- Before export = cat After export = --------------------- Outside Function --------------------- Before export = zebra After export = zebra ---------------------
- 06-08-2008 #3Linux Engineer
- Join Date
- Feb 2005
- Posts
- 1,044
I suspect that the animal variable declared in the outer loop is being "hidden" by the declaration inside the loop. Outside the loop the same variable will be used. It's a scoping issue.
Have you tried the behaviour in the Korn shell to see if it's the same?
- 06-09-2008 #4Just Joined!
- Join Date
- Sep 2006
- Posts
- 4
yeah the behavior is the same in the korn shell using typeset -x


Reply With Quote