Incrementing a variable inside a Bash loop

后端 未结 8 461
挽巷
挽巷 2020-12-29 18:32

I\'m trying to write a small script that will count entries in a log file, and I\'m incrementing a variable (USCOUNTER) which I\'m trying to use after the loop

8条回答
  •  情歌与酒
    2020-12-29 19:03

    I had the same $count variable in a while loop getting lost issue.

    @fedorqui's answer (and a few others) are accurate answers to the actual question: the sub-shell is indeed the problem.

    But it lead me to another issue: I wasn't piping a file content... but the output of a series of pipes & greps...

    my erroring sample code:

    count=0
    cat /etc/hosts | head | while read line; do
      ((count++))
      echo $count $line
    done
    echo $count
    

    and my fix thanks to the help of this thread and the process substitution:

    count=0
    while IFS= read -r line; do
      ((count++))
      echo "$count $line"
    done < <(cat /etc/hosts | head)
    echo "$count"
    

提交回复
热议问题