A variable modified inside a while loop is not remembered

后端 未结 8 2174
挽巷
挽巷 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:28

    I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.

    # reading lines of content from 2 files concatenated
    # inside loop: write value of var i to stderr (before iteration)
    # outside: read var i from stderr, has last iterative value
    
    f=/tmp/file1
    g=/tmp/file2
    i=1
    cat $f $g | \
    while read -r s;
    do
      echo $s > /dev/null;  # some work
      echo $i > 2
      let i++
    done;
    read -r i < 2
    echo $i
    

    Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.

    i=1
    while read -r s;
    do
      echo $s > /dev/null
      let i++
    done <

提交回复
热议问题