Incrementing a variable inside a Bash loop

后端 未结 8 473
挽巷
挽巷 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 18:52

    You're getting final 0 because your while loop is being executed in a sub (shell) process and any changes made there are not reflected in the current (parent) shell.

    Correct script:

    while read -r country _; do
      if [ "US" = "$country" ]; then
            ((USCOUNTER++))
            echo "US counter $USCOUNTER"
      fi
    done < "$FILE"
    

提交回复
热议问题