简体   繁体   中英

Can't understand ps | wc output differences

I was trying to write a set of functions that could check to see if a process name was running when I encountered some unexpected output. I've condensed the issue in the following script names isRunning.sh which depends on a system ps command that can take the '-fC' arguments...

#!/bin/bash
progname=isRunning.sh
ps -fC isRunning.sh
pRet=`ps -fC ${progname} | wc -l`
echo pRet $pRet
psOut=`ps -fC ${progname}` 
wcOut=`echo "${psOut}" | wc -l`
echo
echo ps output
echo "${psOut}"
echo
echo wcOut $wcOut

The first attempt at piping the ps output to wc gets a return of 3. The second attempt gets the expected return value of 2. Can anyone explain this behavior? I figure it's got to be something stupid I am overlooking.

Thanks, bbb

edit: my output

UID        PID  PPID  C STIME TTY          TIME CMD
root      6717  5940  0 13:10 pts/0    00:00:00 /bin/bash ./isRunning.sh
pRet 3

ps output
UID        PID  PPID  C STIME TTY          TIME CMD
root      6717  5940  0 13:10 pts/0    00:00:00 /bin/bash ./isRunning.sh

wcOut 2

I get 2 both attempts. Your ps might be outputting an extra blank line, or somesuch, and then your shell's backtick expansion stripping it. Or maybe you actually had two processes matching the first time you ran it.

If you just want to see if its running, check the exit code from your ps:

if ps -C "${progname}" > /dev/null; then
  echo its running
else
  echo not running
fi

Even better, you should take a look at pidof and pgrep if you can rely on them being present on whichever systems you're targeting. Or use the LSB functions, if you're on Linux.

edit: Actually, since you're looking for copies of yourself running, you might be picking up the shell doing a fork to implement the pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM