巴什变量变化不会持续 [英] Bash variable change doesn't persist

查看:82
本文介绍了巴什变量变化不会持续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的bash脚本来检查,看是否有Python程序正在运行。该计划写出一个PID文件时运行,所以这个比较正在运行的进程的当前目录给我我需要什么。但我有一个变量的问题正在发生变化,然后改变显然回来!这里的脚本:

I have a short bash script to check to see if a Python program is running. The program writes out a PID file when it runs, so comparing this to the current list of running processes gives me what I need. But I'm having a problem with a variable being changed and then apparently changing back! Here's the script:

#!/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是越来越内的所有这些改变,如果语句(即code正在执行如预期),但后来不知怎的又isRunning恢复为0。迷茫......

And the exit value of the bash script is 0. So isRunning is getting changed within all those if statements (ie, the code is performing as expected), but then somehow isRunning reverts to 0 again. Confused...

推荐答案

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

Commands after a pipe | are run in a subshell. Changes to variable values in a subshell do not propagate to the parent shell.

解决方案:改变你的循环

Solution: change your loop to

while read PID; do
    # ...
done < $PIDFILE

这篇关于巴什变量变化不会持续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆