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
  • 5,299
  • 7
  • 16
  • 35
Saeed
  • 381
  • 4
  • 16
  • What would you consider to show it to be running? Using CPU? Generating network traffic? – Andrew Morton May 24 '23 at 19:36
  • 2
    Use another `grep` to filter the first `grep` – Romeo Ninov May 24 '23 at 19:38
  • @AndrewMorton my application first `curl`s a site and downloads a file, then updates the database. I use it in `cron` and I don't want to run multiple downloads at the same time and slowing my network bandwidth. – Saeed May 24 '23 at 19:42
  • @RomeoNinov I think the exit status of `if [ $"(ps aux | grep curl | grep site)" ]; then echo is; else echo not; fi` is always 0 because even this command works as `true`. – Saeed May 24 '23 at 19:43
  • 2
    Which Linux distro? Doesn't `pgrep curl` just work for you? – Destroy666 May 24 '23 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 May 24 '23 at 19:47
  • 2
    I mean `ps aux | grep curl | grep -v grep` – Romeo Ninov May 24 '23 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 May 24 '23 at 19:53

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
  • 5,299
  • 7
  • 16
  • 35
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
  • 18,638
  • 4
  • 48
  • 52
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
  • 5,319
  • 5
  • 20
  • 20