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
8
  • 2
    Use another grep to filter the first grep Commented May 24, 2023 at 19:38
  • 2
    Which Linux distro? Doesn't pgrep curl just work for you?
    – Destroy666
    Commented May 24, 2023 at 19:44
  • 1
    @Destroy666 I use CentOS 9 Stream. pgrep curl works and I tried with both running curl and killing PID. Thanks. Please write it as an answer.
    – Saeed
    Commented May 24, 2023 at 19:47
  • 2
    I mean ps aux | grep curl | grep -v grep Commented May 24, 2023 at 19:47
  • 3
    I think pgreg curl is shorter than ps aux | grep curl | grep -v grep. But Thanks for the comment and answer.
    – Saeed
    Commented May 24, 2023 at 19:53

3 Answers 3

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

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.

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
2
  • ... unless you're curl'ing something served by grep.example.org.
    – asdfex
    Commented May 25, 2023 at 14:20
  • @asdfex, in such case i will grep grep.example.com :) Commented May 25, 2023 at 14:54

Not the answer you're looking for? Browse other questions tagged .