문제

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?

도움이 되었습니까?

해결책

@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

다른 팁

You can do:

tail -f server.log | awk '/Started successfully with/{print "it is working"; system("pkill tail"); exit}'

There is no case of printing "not working" since you're using tail -f and you never know for how long your search string isn't there.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top