3

The script:

$S = 'pgrep -f test.php | wc -l';
$U = trim(shell_exec($S));
echo $U;

Why is the result of this script equal to 0 and sometimes 1 ?

The file test.php is not running.

Mike Doe
  • 16,349
  • 11
  • 65
  • 88
mysql
  • 33
  • 2
  • 2
    because grepping is also a new process, you need to filter grep process from the results. With ps aux you can do: `ps aux | grep test.php | grep -v grep | wc -l` – Agnius Vasiliauskas Jul 27 '18 at 06:52
  • @AgniusVasiliauskas This also works with other commands, piping the result - whichever it might be - to `grep -v pgrep` is a negation which says: "everything **except** what is specified via the `-v` flag". – Tobias F. Jul 27 '18 at 06:58
  • 2
    See [How can I prevent 'grep' from showing up in ps results?](https://unix.stackexchange.com/questions/74185/how-can-i-prevent-grep-from-showing-up-in-ps-results) – Wiktor Stribiżew Jul 27 '18 at 07:09

1 Answers1

3

The problem is while executing the command pgrep -f test.php | wc -l, it will show up itself sometimes (depending on the timing) in the results. You can prevent that according to a question on Linux & Unix SE using the following syntax:

pgrep -f '[t]est.php' | wc -l

The part with the brackets basically says "find the letter t followed by est.php", which will find the file if it is running, but will not match the currently executed command, because after the t follows a bracket [.

Tobias F.
  • 1,050
  • 1
  • 11
  • 23