0

I'm trying to do very likely to this post but instead of reading from a file I want to "subscribe" to the output of adb logcat and every time a new line is logged I will run some code on this line.

I tried these codes, but none worked

tail -f $(adb logcat) | while read; do 
    echo $read;
    processLine $read;
done

or

adb logcat >> logcat.txt &
tail -f logcat.txt | while read; do 
    echo $read;
    processLine $read;
done

What is the simples way to do this? Thanks in advance

Alex P.
  • 30,437
  • 17
  • 118
  • 169
Fnr
  • 2,096
  • 7
  • 41
  • 76

1 Answers1

2

The following two solutions should work. I generally prefer the second form as the wile loop is run in the current process and so I can use local variables. The first form runs the while loop in a child process.

While loop in child process:

#!/bin/bash

adb logcat |
while read -r line; do
  echo "${line}"
  processLine "${line}"
done

While loop in current process:

#!/bin/bash

while read -r line; do
  echo "${line}"
  processLine "${line}"
done < <(adb logcat)
Andrew Vickers
  • 2,504
  • 2
  • 10
  • 16
  • Don't forget the option `-r` to the `read` command. And don't use variables outside of double quotes: `"$line"` (or `"${line}"` with the useless braces). – syme Oct 19 '19 at 20:36
  • @syme: Thanks for the suggestions. I have just got in the habit of ALWAYS enclosing variables in braces. This way, I can never mix two styles in one script. – Andrew Vickers Oct 21 '19 at 00:32
  • using braces is a style ; using double quotes is not (without them, it leads to unexpected/unwanted results). – syme Oct 21 '19 at 18:38
  • @syme. Agree about double quotes, which is why I made that change without commenting on it. – Andrew Vickers Oct 22 '19 at 14:54
  • inotifywait is the tool for this. – wuseman Oct 23 '19 at 05:20