Shell variable scope

I have recently been doing some fairly involved shell programming on
QNX 6.1. My background is several years of work on HP-UX.

I am seeing a behavior in shell scripts that I never saw, so I wonder if
it’s somehow specific to QNX.

If I set a variable value within a loop, the variable is inevitably null upon breaking from the loop. This is true even if I “declare -x” the variable
at the head of script. It’s as if a block scope is being observed, and
variables set within the loop act as if they were declared there and
are not valid outside the loop block. I have tried bash and ksh both - same behavior.

Am I crazy? Has anyone else seen this? It’s completely contrary to all
shell documentation.

Thanks,
Randy C.

Can you please post a test code?

I don’t have QNX 6.1, but the following test code works for me as expected in QNX 6.2.1

#!/bin/sh

var1=test
echo $var1

for i in 1 2 3 4
do
 echo $i
 if [ $i -eq 2 ]; then
   var1=test2
   var2=new
   break
 fi
done
echo $i
echo $var1
echo $var2

output

test
1
2
2
test2
new

Now I’m confused and embarrassed because I can’t reproduce the problem. I don’t have a ready example, because I already restructured the code where I was seeing this issue.

I wonder if I was doing something insane, like not breaking out of the loop, and later reassigning my key variable to null.

If I get this behavior again, I’ll be back and post the guilty code.

Thanks,
Randy C.