Bash variable change doesn't persist

前端 未结 2 515
[愿得一人]
[愿得一人] 2020-12-22 10:53

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 p

相关标签:
2条回答
  • 2020-12-22 11:23

    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
    
    0 讨论(0)
  • 2020-12-22 11:23

    It's the pipe that is the problem. Using a pipe in this way means that the loop runs in a sub-shell, with its own environment. Kill the cat, use this syntax instead:

    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"
    
    0 讨论(0)
提交回复
热议问题