如何在脚本中停止tail命令

Bor*_*yev 12 unix linux bash

我想做什么 - 使用自定义ssh客户端代码***开始将更改捕获到日志文件.经过一段时间(不是固定值并且基于事件),发出命令以停止拖尾.这是我用来捕获日志文件的最新更改的命令 - tail -f logfile.txt

我想能够用:q脚本发出的东西来结束它.我不想像键盘命令那样ctrl + c.

***我的自定义ssh客户端代码的伪代码(用oop语言编写)

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;
Run Code Online (Sandbox Code Playgroud)

我没有对日志文件所在服务器的写访问权限.

我尝试了什么 - http://www.linuxquestions.org/questions/red-hat-31/how-to-stop-tail-f-in-scipt-529419/

我无法理解那里的解决方案(在帖子2中).有人可以解释解决方案或建议采用不同的方法吗?

谢谢.

anu*_*ava 21

在脚本中,您可以使用$!变量.

# 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
Run Code Online (Sandbox Code Playgroud)

$! 扩展到最近执行的后台(异步)命令的进程ID.

  • `&1`不是文件,而是对文件描述符= 1的引用,即stdout.您可能需要阅读unix中有关重定向的一些基本教程.如果你想把它保存在一个文件中,那么使用`tail -f /var/log/sample.log> /tmp/file.out 2>&1&`假设你有权写入`/ tmp/file.out` (2认同)