How do I stop tail command in script

bash, linux, unix

Solution

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.

Problem

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.

Original source

Related problems