Different versions / implementations of shells handling subshells differently. Every pipe makes a copy of the process then runs exec to run the command you wanted. So the count isn't incorrect, exactly.
change your grep to use a regexp to search so that the search doesn't match itself. Otherwise you may see two matches... one for the process you wanted and one for your grep itself. It will vary from system to system and in some cases can vary on the same system.
Looks like parent shell is creating new shell to run the command. Is there a way to avoid this? Goal is to have same code to run on AIX and Linux ksh shell.
To keep the forums high quality for all users, please take the time to format your posts correctly.
First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags
```text
and
```
by hand.)
Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.
Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.
As said earlier, pipes do a fork/exec. And while the exec is not yet ready there is a cloned shell. This is a race condition.
To avoid the race conditions you must avoid sub-shells and pipes and maybe even calling external programs.
The best thing is pgrep . Unfortunately AIX does not have it.
cjcox and Aia solutions combined is maybe good enough:
--
Someone mentioned the lockfile method.
If the purpose is to prevent multiple instances to run, then indeed the lockfile method seems better than the process method.