Incrementing a variable inside a Bash loop

后端 未结 8 453
挽巷
挽巷 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
    • Always use -r with read.
    • There is no need to use cut, you can stick with pure bash solutions.
      • In this case passing read a 2nd var (_) to catch the additional "fields"
    • Prefer [[ ]] over [ ].
    • Use arithmetic expressions.
    • Do not forget to quote variables! Link includes other pitfalls as well
    while read -r country _; do
      if [[ $country = 'US' ]]; then
        ((USCOUNTER++))
        echo "US counter $USCOUNTER"
      fi
    done < "$FILE"
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题