Find the answer to your Linux question:
Results 1 to 4 of 4
Hi All Attached is a script that sets two variables in two different loops. After the first loop the variables are set to their original values for some or other ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Jan 2006
    Location
    South Africa, Pretoria
    Posts
    4

    Shell programming problems


    Hi All

    Attached is a script that sets two variables in two different loops. After the first loop the variables are set to their original values for some or other reason.

    The second loop also sets the same variables using the same function but retains their values as set in the second loop. I am running SUSE 8 enterprise.

    Does anyone perhaps know why the values are not set after the first loop?

    Code:
    #!/bin/bash
    
    Change() {
    
       STRINGVAR="CHANGED"
       echo "$STRINGVAR + $INT"
       let INT=$INT+1
    }
    
    STRINGVAR="START"
    typeset -i INT=0
    
    
    ps -ef | while read line
    do
       Change
    done
    
    echo "AFTER FIRST LOOP BLOCK = " $STRINGVAR
    echo "AFTER FIRST LOOP BLOCK = " $INT
    
    while [ $INT -le 10 ]
    do
            Change
    done
    
    echo "AFTER SECOND LOOP BLOCK = " $STRINGVAR
    echo "AFTER SECOND LOOP BLOCK = " $INT
    OUTPUT
    ------------------------------------------------------------
    CHANGED + 0
    CHANGED + 1
    CHANGED + 2
    CHANGED + 3
    .
    .
    .
    CHANGED + 176
    AFTER FIRST LOOP BLOCK = START
    AFTER FIRST LOOP BLOCK = 0

    CHANGED + 0
    CHANGED + 1
    CHANGED + 2
    CHANGED + 3
    CHANGED + 4
    CHANGED + 5
    CHANGED + 6
    CHANGED + 7
    CHANGED + 8
    CHANGED + 9
    CHANGED + 10
    AFTER SECOND LOOP BLOCK = CHANGED
    AFTER SECOND LOOP BLOCK = 11

  2. #2
    Linux Guru lakerdonald's Avatar
    Join Date
    Jun 2004
    Location
    St. Petersburg, FL
    Posts
    5,035
    1. Please put code in [code] tags
    2. I don't know why this is, I was under the impression that bash variables were global...
    Oh well.

  3. #3
    Just Joined!
    Join Date
    Jan 2006
    Posts
    2
    Does anyone perhaps know why the values are not set after the first loop
    Yes, that's because of the pipe. Every part of a pipe run inside a separate subshell. You can prove this trying:

    ps -ef> $tm_file
    while read line
    do
    Change
    done< $tmp_file

    Bye

  4. #4
    Linux Guru lakerdonald's Avatar
    Join Date
    Jun 2004
    Location
    St. Petersburg, FL
    Posts
    5,035
    Quote Originally Posted by sant
    Yes, that's because of the pipe. Every part of a pipe run inside a separate subshell.
    This isn't true on all shells on all Unices however, I don't think.

Posting Permissions

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