【问题标题】:Tail file till process exits尾文件直到进程退出
【发布时间】:2017-01-26 21:26:47
【问题描述】:

查看superuser 的答案。

我正在尝试修改它以侦听多个字符串并回显自定义消息,例如 ; '您的服务器已成功启动' 等

我也在尝试将它附加到另一个命令,即 pip

wait_str() {
  local file="$1"; shift
  local search_term="Successfully installed"; shift
  local search_term2='Exception'
  local wait_time="${1:-5m}"; shift # 5 minutes as default timeout

  (timeout $wait_time tail -F -n0 "$file" &) | grep -q "$search_term" && echo 'Custom success message' && return 0 || || grep -q "$search_term2" && echo 'Custom success message' && return 0

  echo "Timeout of $wait_time reached. Unable to find '$search_term' or '$search_term2' in '$file'"
  return 1
}

我想到的用法是:

pip install -r requirements.txt > /var/log/pip/dump.log && wait_str /var/log/pip/dump.log

为了澄清,我想让 wait_str 在 pip 退出时停止拖尾,无论成功与否。

【问题讨论】:

  • @PS。 tail 命令不会退出。我需要这样做tail -f /var/log/pip/stderr.log | awk '/Exception/ { system("echo worked!")}' || awk '/compiler/ { system("echo worked!")}' 来测试两个字符串。
  • 您似乎假设这些命令并行运行,但您的命令显示串行执行。根据定义,pip 将在wait_str 运行时完成,因为您将它们与&& 连接,它等待pip 并检查其退出状态,然后仅当pip 成功时运行wait_str

标签: python linux bash shell pip


【解决方案1】:

以下是一般答案,tail 可以替换为任何导致行流的命令。

如果不同的字符串需要不同的操作,那么使用以下操作:

tail -f var/log/pip/dump.log |awk '/condition1/ {action for condition-1} /condition-2/ {action for condition-2} .....' 

如果多个条件需要相同对其进行操作,请使用 OR 运算符将它们分开:

tail -f var/log/pip/dump.log |awk '/condition-1/ || /condition-2/ || /condition-n/ {take this action}'

基于 cmets : Single awk 可以做到这一点。

tail -f /path/to/file |awk '/Exception/{ print "Worked"} /compiler/{ print "worked"}'  

tail -f /path/to/file | awk '/Exception/||/compiler/{ print "worked"}' 

如果找到匹配则退出

tail -f logfile |awk '/Exception/||/compiler/{ print "worked";exit}'

【讨论】:

  • 谢谢!刚刚测试过它可以工作。我正在从脚本中调用tail,我需要它退出以便脚本可以继续执行。
  • 这个( tail -f -n0 logfile.log & ) | grep -q "Server Started" 在找到字符串时退出管道(从超级用户站点复制过来)。我从未使用过 awk 是否有类似的选项可以在找到字符串后允许退出?
  • 是的,确实,一旦找到字符串,您就可以退出 awk。在 awk 中使用 print 语句后的 exit,例如:awk '/Exception/||/compiler/{ print "worked";exit}'
  • 太棒了!感谢您的精彩回答!
  • 我在运行tail -f logfile |awk '/Exception/||/compiler/{ print "worked";exit}' 时使用 Ctrl^C 来停止 tail。尝试添加第二个;exit 比赛结束后单线中是否有退出尾巴的方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多