Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop tail command in script

Tags:

linux

bash

unix

What I want to do - Start capturing the CHANGES to a log file using a custom ssh client code***. After some time (which not a fixed value and is event based), issue a command to stop tailing. This is the command I use to capture the latest changes to a log file - tail -f logfile.txt

I want to be able to end it with something like :q which I can issue from a script. I don't want to keyboard commands like ctrl + c.

*** Pseudo code for my custom ssh client code (written in an oop language)

include ssh-api
ssh = getSSHConnection();
cmd = 'cd to folder';
ssh.command(cmd);
cmd = 'tail -f log.txt';
ssh.command(cmd);
wait for special event to occur...
cmd = 'stop the tail now!'
out = ssh.command(cmd);
print "the changes made to log file were\n"  + out;

I have no write access to the server where the log file is located.

What I tried - http://www.linuxquestions.org/questions/red-hat-31/how-to-stop-tail-f-in-scipt-529419/

I am not able to understand the solution there (Its in post 2). Can someone please explain the solution or suggest a different way to do this?

Thank you.

like image 387
Erran Morad Avatar asked Feb 19 '15 06:02

Erran Morad


People also ask

How do you terminate tail command?

In less , you can press Ctrl-C to end forward mode and scroll through the file, then press F to go back to forward mode again. Note that less +F is advocated by many as a better alternative to tail -f .

How do you exit a tail command in Unix?

To stop it, press Ctrl + C . This is a useful example of using tail and grep to selectively monitor a log file in real time. In this command, tail monitors the file access. log.

How do I get out of tail command in putty?

command(cmd); wait for special event to occur... cmd = 'stop the tail now!

How do you stop a script execution in Linux?

If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.


1 Answers

Inside your script you can make use of $! variable.

# run tail -f in background
tail -f /var/log/sample.log > out 2>&1 &

# process id of tail command
tailpid=$!

# wait for sometime
sleep 10

# now kill the tail process
kill $tailpid

$! Expands to the process ID of the most recently executed background (asynchronous) command.

like image 103
anubhava Avatar answered Sep 21 '22 20:09

anubhava