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.
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 .
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.
command(cmd); wait for special event to occur... cmd = 'stop the tail now!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With