Reputation: 1371
I'm writing a unix shell script and need to check if there are currently running processes with "xyz" in their directory. If yes than continue to next command and show text like "Found It".
If not than don't continue and display text like "Process Not Found".
I tried something like this:
if ps -ef | grep xyz
then
echo "XYZ Process Found!"
else
echo "XYZ Process Not Found!"
fi
But it just showing me the processes and display "process found" even if there's no xyz process.
Upvotes: 1
Views: 7653
Reputation: 3950
is_xyz_running() {
[ "$(pgrep xyz)" ] && echo true || echo false
}
Upvotes: 0
Reputation: 201537
I believe you want to check the output of the command against a value using Command substition, from the linked bash-hackers wiki The command substitution expands to the output of commands. These commands are executed in a subshell, and their stdout data is what the substitution syntax expands to. Also, count the lines and remove grep. Something like,
if [[ $(ps -ef | grep xyz | grep -v grep | wc -l) != 0 ]]; then
echo "XYZ Process Found!"
else
echo "XYZ Process Not Found!"
fi
Edit
Based on the comments below, you should probably use
if [[ $(ps -ef | grep -c xyz) -ne 1 ]]; then
which is a lot easier to read.
Upvotes: 5
Reputation: 20980
When you run grep xyz
, that process - grep xyz
- is also running & thus shown in the output of ps -ef
.
This running process command line contains xyz
. Thus grep passes that line to output.
Hence you always get zero exit status - i.e. success.
2 Solutions:
use if ps -ef | grep '[x]yz'; then
. (You may want to suppress grep
output with -q
)
The grep command being run is grep [x]yz
. This gets printed in ps -ef
output.
Obviously, grep filters out this line. [x]yz
could be matched with \[x\]yz
, not with [x]yz
.
use if pgrep -f xyz >/dev/null; then
Check man pgrep
for more details..
Upvotes: 3
Reputation: 27852
You can also use pgrep
. From pgrep(1)
:
pgrep looks through the currently running processes and lists the process IDs which match the selection criteria to stdout.
[...]
EXIT STATUS
0 One or more processes matched the criteria.
1 No processes matched.
2 Syntax error in the command line.
3 Fatal error: out of memory etc.
Example output:
[~]% pgrep xterm
18231
19070
31727
You can use it in an if
statement like so:
if pgrep xterm > /dev/null; then
echo Found xterm
else
echo xterm not found
fi
Note: pgrep
is not a standard utility (ie. it's not in POSIX), but widely available on at least Linux and I believe most BSD systems.
Upvotes: 2