4

I want to check if a command is running with the following if clause, but it's always true, whether command actually is running or not:

if [ $"(ps aux | grep curl)" ]; then echo is; else echo not; fi

Result:

[root@is ~]# if [ $"(ps aux | grep curl)" ]; then echo is; else echo not; fi
is

The ps command outside of if:

[root@is ~]# ps aux | grep curl
root      216564  0.0  0.2   6408  2064 pts/0    S+   22:22   0:00 grep --color=auto curl

How can I check if curl in my example is running or not?

I tried with different arguments of ps, but I always have the grep command (which is normal in my mind), but I don't know how to check that if it's running or not.

Update 1

I'm thinking that I can do this but I don't know how to do this in commands:

if ps aux blah
  if it has only one line (I suppose somehow use `wc -l`
    then do something
  else do something else
  fi
fi
Destroy666
  • 12,350
Saeed
  • 443

3 Answers3

11

You can just use pgrep curl, which returns process ID(s) only if a running process is found. Example:

[  -n "$(pgrep curl)" ] &&  echo "yes" || echo "no"

pgrep documentation

Destroy666
  • 12,350
8

The common trick to skip the line with the grep itself is to use some kind of a regex:

ps aux | grep '[c]url'

The commmand itself now doesn't contain the string curl itself, so it won't match.

choroba
  • 20,299
2

One possible way is to add another grep to filter the grep process
instead of

ps aux | grep curl

make it

ps aux | grep curl | grep -v grep
Romeo Ninov
  • 7,848