Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2004

    Unanswered: Variable scope and debugging


    How is a variable's scope handled in bash? Here's the code skeleton.

    while read oneLine
    # do some mathematics with $var
    # and the value read from the file

    echo $var # displays variable value correctly for each stage

    done < $inputFile

    echo "Loop done.. $var" # displays accumulated variable value as 0

    When I write set -a var it works, but I'm unable to debug the script any more by specifying set -x. Can we not do both at the same time?

    Thanks in advance.

    - Ram.

  2. #2
    Join Date
    Jan 2004
    Bordeaux, France
    I am using cgywin bash and i don't have this problem :
    echo "Before loop Pid:$$ Var:$Var"
    while read oneline
       ((Var += 1))
        echo "   Inside loop Pid:$$ Var:$Var"
    done < a.a
    echo "After loop Pid:$$ Var:$Var"
    the result is :
    Before loop Pid:429381 Var:0
    Inside loop Pid:429381 Var:1
    Inside loop Pid:429381 Var:2
    Inside loop Pid:429381 Var:3
    Inside loop Pid:429381 Var:4
    Inside loop Pid:429381 Var:5
    Inside loop Pid:429381 Var:6
    After loop Pid:429381 Var:6
    Some version of shell creates a subprocess to execute the statements into the loop, in that case the modifications of the environment are lost when exiting the loop.
    Try my script and verify that the Pid is the pid is the same outside and inside the loop.

    You can also try to export your variable.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts