Reputation: 61
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?
Upvotes: 3
Views: 517
Reputation: 437688
@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.(...)
instead of command grouping { ...; }
(slightly less efficient).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
Upvotes: 3
Reputation: 785126
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.
Upvotes: 2