A variable modified inside a while loop is not remembered

后端 未结 8 2177
挽巷
挽巷 2020-11-21 05:06

In the following program, if I set the variable $foo to the value 1 inside the first if statement, it works in the sense that its value is remember

8条回答
  •  广开言路
    2020-11-21 05:32

    How about a very simple method

        +call your while loop in a function 
         - set your value inside (nonsense, but shows the example)
         - return your value inside 
        +capture your value outside
        +set outside
        +display outside
    
    
        #!/bin/bash
        # set -e
        # set -u
        # No idea why you need this, not using here
    
        foo=0
        bar="hello"
    
        if [[ "$bar" == "hello" ]]
        then
            foo=1
            echo "Setting  \$foo to $foo"
        fi
    
        echo "Variable \$foo after if statement: $foo"
    
        lines="first line\nsecond line\nthird line"
    
        function my_while_loop
        {
    
        echo -e $lines | while read line
        do
            if [[ "$line" == "second line" ]]
            then
            foo=2; return 2;
            echo "Variable \$foo updated to $foo inside if inside while loop"
            fi
    
            echo -e $lines | while read line
    do
        if [[ "$line" == "second line" ]]
        then
        foo=2;          
        echo "Variable \$foo updated to $foo inside if inside while loop"
        return 2;
        fi
    
        # Code below won't be executed since we returned from function in 'if' statement
        # We aready reported the $foo var beint set to 2 anyway
        echo "Value of \$foo in while loop body: $foo"
    
    done
    }
    
        my_while_loop; foo="$?"
    
        echo "Variable \$foo after while loop: $foo"
    
    
        Output:
        Setting  $foo 1
        Variable $foo after if statement: 1
        Value of $foo in while loop body: 1
        Variable $foo after while loop: 2
    
        bash --version
    
        GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
        Copyright (C) 2007 Free Software Foundation, Inc.
    

提交回复
热议问题