Incrementing a variable inside a Bash loop

后端 未结 8 479
挽巷
挽巷 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"
    

提交回复
热议问题