Search code examples
linuxbashcopy-pastetail

Self stopping tail operation


I needed some help for following:

In a menu a tail operation will be carried out and then after a certain output the tail will get terminated and we will get back to the menu.

tail -f server.log |
  grep "Started successfully with " &&
  echo "it is working" ||
  echo "not working"

Can anyone help me to have a self-closing tail command?


Solution

  • @anubhava's answer works, but there is no need for awk:

    The key is to use grep with -m1, which makes it return once a match is found, at which point the tail process can be killed:

    tail -f server.log | 
      { grep -m1 "Started successfully with " && pkill -P $$ -x tail; }
    
    • -P $$ (considers only child processes of the current shell) and -x (matches process name exactly) ensure that only the tail process of interest is killed.
    • You could also use a subshell (...) instead of command grouping { ...; } (slightly less efficient).
    • If the string is not found, grep only returns in the event that tail is externally killed - to report this case, add a || clause; e.g., || echo 'ERROR: tail -f was killed' >&2