0

I want to read a specific value from a /proc file, and currently that's done in a 'while read line' loop, as a scheleton:

while read line
do
    if [[ $line = *MATCHES STRING* ]]; then
        for ((  i=0 ;  i<=$someVAR-1;  i++ ))
        do
          [if statement to check if the specific line is not equal with 0]
          then [whatever]
        done
    fi
done < "/proc/FILE"

With that, I want to further improve the loop so that I can make count of how many times the if statement inside the for loop returns a value above 0. So the stop conditions should be like:

if line matches string then
for loop
do
use a variable to keep count that the conditions has been met 2 times.

When that occurs, the loop should stop and show a message.

5
  • An example might help. Commented Feb 27, 2014 at 9:49
  • 1
    Increment a variable in the if statement. After the loop, test the variable, and use break to stop the loop. Commented Feb 27, 2014 at 9:52
  • is it possible to grep "MATCHES STRING" in the file & store result in line? Commented Feb 27, 2014 at 9:57
  • Hi Barmar - testing the new variable value will have to be done outside the while read line loop, so break will not work. Commented Feb 27, 2014 at 10:09
  • @user3144292 i think @Barmar give you solution it's vary right to increment count variable in if (inside for loop if) and check that count outside in while and use break to stop. simple Commented Feb 27, 2014 at 12:00

1 Answer 1

1
while read line
do
    if [[ $line = *MATCHES STRING* ]]; then
        count=0
        for ((  i=0 ;  i<=$someVAR-1;  i++ ))
        do
            [if statement to check if the specific line is not equal with 0]
            then count=$((count+1))
            fi
        done
        if [[ $count -ge 2 ]]
        then break
        fi
    fi
done < "/proc/FILE"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Barmar! I moved the if count outside the while loop as in particular I want to have it go through the entire lines and data. But again, your answer was very helpful!
Your question says when that occurs, the loop should stop. How can you stop the loop if you do the test outside the loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.