Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to continue run script after tail -f command

Tags:

bash

tail

signals

I have the following script:

tail -f nohup.out
echo 5

When I press Ctrl+C on tail -f, the script stops running: the 5 is not printed. How can I run the command echo 5 after I stop the tail command?

like image 584
Richard Avatar asked Aug 14 '12 11:08

Richard


2 Answers

Ctrl+C sends the SIGINT signal to all the processes in the foreground process group. While tail is running, the process group consists of the tail process and the shell running the script.

Use the trap builtin to override the default behavior of the signal.

trap " " INT
tail -f nohup.out
trap - INT
echo 5

The code of the trap does nothing, so that the shell progresses to the next command (echo 5) if it receives a SIGINT. Note that there is a space between the quotes in the first line; any shell code that does nothing will do, except an empty string which would mean to ignore the signal altogether (this cannot be used because it would cause tail to ignore the signal as well). The second call to trap restores the default behavior, so that after the third line a Ctrl+C will interrupt the script again.

like image 167
Gilles 'SO- stop being evil' Avatar answered Nov 03 '22 02:11

Gilles 'SO- stop being evil'


#!/bin/bash
trap "echo 5" SIGINT SIGTERM
tail -f nohup.out
like image 35
matteomattei Avatar answered Nov 03 '22 00:11

matteomattei