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.
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 ?

  • How does the script know when to stop tailing? Jul 21, 2014 at 9:26
  • @richard let the user to stop the tail, press some special key for example Jul 21, 2014 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"). Jul 21, 2014 at 9:37

2 Answers 2


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 &
...do some other stuff...
kill $tailpid
...carry on...

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 &
sleep 60
kill $tail_pid

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .