1

I have this:

while [ "ps aux | grep '[0]:00 Xvfb :99 -screen 0 1024x768x16'" ]
do 
    echo "sleep"
    ps aux | grep "[0]:00 Xvfb :99 -screen 0 1024x768x16"
    sleep 1
done

This gives me:

sleep
sleep
sleep
sleep
sleep
sleep
root         7  0.5  1.5 207336 31620 ?        Sl   09:31   0:00 Xvfb :99 -screen 0 1024x768x16
sleep
root         7  0.4  1.5 207336 31620 ?        Sl   09:31   0:00 Xvfb :99 -screen 0 1024x768x16
sleep
root         7  0.3  1.5 207336 31620 ?        Sl   09:31   0:00 Xvfb :99 -screen 0 1024x768x16
...
...
...

How can I change my oneliner so that the loop is exited once the ps aux | grep returns 0 (meaning the Xvfb process is running)?

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
fredrik
  • 9,631
  • 16
  • 72
  • 132

1 Answers1

7

At the moment, you're evaluating whether a string is non-empty (in bash, [ "string" ] is equivalent to [ -n "string" ]).

If you want to exit when the pattern is matched, use this:

while ! ps aux | grep -q '[0]:00 Xvfb :99 -screen 0 1024x768x16'; do 
    echo "sleep"
    sleep 1
done

The -q option to grep enables "quiet mode", so output is supressed.

Note that you could (should?) use pgrep instead of your pipe:

while ! pgrep '0:00 Xvfb :99 -screen 0 1024x768x16'; do
# ...
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • In some situations `[[` behaves less surprising, which is why I prefer `[[` over `[`. (See also: https://stackoverflow.com/questions/669452/is-preferable-over-in-bash-scripts) – Micha Wiedenmann Aug 31 '16 at 09:48
  • @Micha agreed that `[[` has its uses in bash scripts but `[[ "string" ]]` behaves just the same as `[ "string" ]` and here, we don't even want to use `test` (or the bash extended version) at all! – Tom Fenech Aug 31 '16 at 09:51