Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a ksh script, in which I use tail -f to view a log file.

How can I terminate the tail process, and continue executing the underlying script?

I am running it on AIX 7.1.
---------------------------------------------edit-----------------------------------
according to Gilles's answer, I tried this in my script:

trap 'echo "tail process terminated!"' 2
tail -f mylog.log
trap - 2

Now after tail command get executed, then I press CTRL+C, the tail process was killed, and my script continue to run. But the new problem is , when I press CTRL+C again, my script will not exit. Any one can help ?

share|improve this question
    
How does the script know when to stop tailing? –  richard Jul 21 at 9:26
    
@richard let the user to stop the tail, press some special key for example –  CaiNiaoCoder Jul 21 at 9:28
    
look at @flup's answer. You will have to add something to read the key, before the kill (there it says "do some other stuff"). –  richard Jul 21 at 9:37
    
@richard thanks, I will try it later. –  CaiNiaoCoder Jul 21 at 9:55

2 Answers 2

up vote 1 down vote accepted

The point of tail -f is to run forever until explicitly killed, so you'll have to arrange to kill it.

If there is some logic that determines when the tail process is to be killed, obtain the process ID of tail and arrange to trigger its killing when desired. For example, if you want to kill it after a minute:

tail -f file.log &
tail_pid=$!
sleep 60
kill $tail_pid
do_more_stuff

If you want to terminate tail but not the shell script when the user presses Ctrl+C, trap the SIGINT signal. You need to set the trap to a non-empty string (any non-empty value will do, even a space) since an empty string would cause SIGINT to be ignored by the tail subprocess as well as by the calling shell.

trap : INT       # set a signal handler for SIGINT that does nothing
tail -f file.log
do_more_stuff    # executed when tail is killed, e.g. by the user pressing Ctrl+C
trap - INT       # reset SIGINT to killing the script
share|improve this answer

If you don't background the tail command in your script, the shell will wait for it to exit, which will never happen.

If you have other work to do, after which you want to kill the tail command, you can

tail -f logfile &
tailpid=$!
...do some other stuff...
kill $tailpid
...carry on...
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.