0

我有一个简短的 bash 脚本来检查 Python 程序是否正在运行。该程序在运行时会写出一个 PID 文件,因此将其与当前正在运行的进程列表进行比较可以满足我的需求。但是我遇到了一个变量被更改然后显然又变回来的问题!这是脚本:

#!/bin/bash
# Test whether Home Server is currently running
PIDFILE=/tmp/montSvr.pid
isRunning=0
# does a pid file exist?
if [ -f "$PIDFILE" ]; then
  # pid file exists
  # now get contents of pid file
  cat $PIDFILE | while read PID; do
    if [ $PID != "" ]; then
      PSGREP=$(ps -A | grep $PID | awk '{print $1}')
      if [ -n "$PSGREP" ]; then
        isRunning=1
        echo "RUNNING: $isRunning"
      fi
    fi
  done
fi
echo "Running: $isRunning"
exit $isRunning

当 Python 脚本运行时,我得到的输出

RUNNING: 1
Running: 0

并且 bash 脚本的退出值为 0。所以 isRunning 在所有这些 if 语句中都发生了变化(即,代码按预期执行),但随后不知何故 isRunning 再次恢复为 0。使困惑...

4

2 回答 2

6

管道之后的命令在|子 shell 中运行。对子 shell 中变量值的更改不会传播到父 shell。

解决方案:将循环更改为

while read PID; do
    # ...
done < $PIDFILE
于 2012-11-05T13:53:57.017 回答
0

问题出在管道上。以这种方式使用管道意味着循环在具有自己的环境的子外壳中运行。杀死cat, 改为使用以下语法:

while read PID; do
    if [ $PID != "" ]; then
      PSGREP=$(ps -A | grep $PID | awk '{print $1}')
      if [ -n "$PSGREP" ]; then
        isRunning=1
        echo "RUNNING: $isRunning"
      fi
    fi
  done < "$PIDFILE"
于 2012-11-05T13:55:23.560 回答