【问题标题】:Bash init script skips reading commands in if loopBash init 脚本在 if 循环中跳过读取命令
【发布时间】:2019-04-25 15:16:29
【问题描述】:

我正在尝试为 bash 中的程序创建一个初始化脚本。 (rhel6)

它首先检查进程。如果找到进程,它将回显该程序已经在线,如果没有,它将继续使用启动脚本以特定用户身份启动该程序。之后,它应该跟踪程序的日志文件并一起检查一串单词。如果找到的话,它应该杀死尾巴并回显该程序在线。

这是开始部分。

prog=someProg
user=someUser
threadCount=$(ps -ef | grep $prog |grep -v 'grep' |awk '{ print $2 }'| wc -l)

startb() {
  if [ "$threadCount" -eq 2 ]; then
    echo "$prog already online."
  else
    echo "Bringing $prog online."
    su $user -c "/path/to/start/script.sh"
    tail -f /path/to/$prog/log/file |
      while IFS=$'\n' read line
        do
          if [[ $line == *started\ up\ and\ registered\ in* ]]; then
            pkill tail
            echo "$prog now online."
          fi
        done
  fi
}

我的问题:

  1. 变量 $prog 没有在 $threadcount 中被选中 不管我怎么尝试。 (带单引号和双引号)
  2. 跟踪日志文件的逻辑是随机运行的。有时它 简直完美。它拖尾并等待直到找到字符串 在回显程序在线之前,有时它只是启动脚本 然后回显该程序在线,无需等待或等待。

这是不可预测的。我也在停止段中实现了相同的逻辑来监控日志然后回显,但即使它的工作方式与启动相同。只是随机的。

我确信这可能看起来很愚蠢和破碎。这是通过我的初学者 bash 技能到处挑选碎片制成的。

提前感谢您的建议和帮助。

【问题讨论】:

  • pkill tail 会尝试杀死所有的尾巴。我知道这不是你的问题,只是一个观察。

标签: bash shell startup init rhel6


【解决方案1】:

我无法重现您在使用“grep $prog”时遇到的错误...抱歉。

但对于另一部分。

  1. 我将假设启动程序的脚本,即带有 su 的行,正在后台启动某些内容,并且脚本自行结束。如果没有,您的示例将无限期等待。

  2. 可能是个人喜好,但是当我使用 tail 之类的东西来验证行时,我使用命名管道 (mkfifo)。

这会给出类似的东西:

# Getting the tail in background
tail -f /path/to/$prog/log/file > some_fifo &
# Getting the tail PID
tailPID=$!

while read line; do #You don't need to modify/use IFS here.
     if [[ $line == *started\ up\ and\ registered\ in* ]]; then
           kill -15 $tailPID #since you know the PID you won't kill another tail
           echo "$prog now online."
           break # don't like the possibility, even remote, of an infinite loop :)
     fi
done < some_fifo #reading from the named pipe

希望对你有帮助

【讨论】:

  • 非常感谢您的意见安德烈!你的猜测是对的。它只是用加载参数启动java程序的命令,然后将所有内容都扔给dev null。对于第一个,我没有收到任何错误。假设我声明了变量 $prog=someProg 并且当我使用命令时.. ps -ef | grep $prog ..正如预期的那样,它应该这样做.. ps -ef| grep someProg 但它实际上是在寻找 $prog 并回显该程序未运行。显然没有以该名称运行的程序。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 2014-10-04
  • 2019-05-06
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
相关资源
最近更新 更多