Search code examples
bashshellwc

wc -l Sometimes Outputs Wrong Number


I have some code like this:

while true
do
    who | cut -d' ' -f1 | sort | grep -v "erik" > "/home/erik/logintester/users.txt"

    lines=$(< "/home/erik/logintester/users.txt" wc -l)

    echo "$lines"

done

It's supposed to echo a "1" whenever there is another person logged in, but instead I get 1's and 0's mixed in. Is there a fix to this problem? Any suggestions are highly appreciated.


Solution

  • Assuming BOC's suggestion of a second process interfering is correct, you are contributing to the problem by using an unnecessary file (which provides a shared resource that allows the race condition to occur).

    All you need is a single pipeline. (Capturing the output of the pipeline in order to call echo is also unnecessary.)

    while true; do
        who | cut -d' ' -f1 | sort | grep -v "erik" | wc -l
    done
    

    You can simply it further by using a single call to awk (the sort doesn't seem to serv any purpose; the count is the same no matter what order the output is in):

    while true; do
        who | awk '$1 != "erik" {count+=1} END {print count}'
    done