zhaojing
zhaojing

Reputation: 625

shell: how to make tail of a file running in background

I want to run a few tasks in shell.

  1. tail a file into a new file: for example: tail -f debug|tee -a test.log
  2. at the same time, run other tasks.

My question is: how to make the command tail -f debug|tee -a test.log run in background, so that I can run other tasks then in shell script?

Upvotes: 6

Views: 15283

Answers (4)

Dani
Dani

Reputation: 1

In addition, you can see the running tails with the command 'jobs'. For example:

[root@OS4 tufin-admin]# tail -F /var/log/to.log > /tmp/to &
[3] 674697
[root@OS4 tufin-admin]# jobs -pl
[1]  650033 Running                 kubectl logs -f -l app=rma > /tmp/rma &
[2]- 674286 Running                 tail -F var/log/journal/d1524a98a19d4ab59b9ccf9749e3d595/system@d439ce74822b4836ab58a88b6a65d200-0000000000014a12-00060d1140dd3307.journal > /tmp/journal &
[3]+ 674697 Running                 tail -F /var/log/to.log > /tmp/to &

Upvotes: 0

Michael Dillon
Michael Dillon

Reputation: 32392

The simple way to do this is:

screen -R -D
tail -f debug|tee -a test.log
Ctrl-A c
ps ax |grep tail
Ctrl-A [Backspace]
...
Ctrl-A [Spacebar]

screen lets you run multiple terminal sessions on one terminal connection. You switch back and forth with Ctrl-A [Backspace]|[Space]. To create another separate shell Ctrl-A c

A major benefit of screen is that if the terminal session disconnects, it keeps everything runnning. Just close the terminal window or disconnect ssh, go to another computer, log in and run screen -R -D to reconnect to everything which is still running.

If you only occasionally need this, just run tail, type Ctrl-Z, run a command, then fg %1 to bring the tail process back into the foreground, or bg %1 to make it run in the background permanently. If you do use Ctrl-Z, then the jobs command shows all of your detached jobs.

Upvotes: 3

Jason Striegel
Jason Striegel

Reputation: 1063

Normally you just use an ampersand after the command if you want to background something.

tail -f debug|tee -a test.log &

Then you can bring it back to the foreground later by typing fg. Did this answer your question or have I missed what you were asking?

Upvotes: 5

evil otto
evil otto

Reputation: 10582

You don't need tee at all for this, just use the shell's built-in append operator:

tail -f debug >> test.log &

The trailing & works as normal in the shell. You only need tee to send the output to a file as well as standard out, which if you have it in the background probably isn't what you want.

Upvotes: 8

Related Questions