1

I want to check the current version of python is the one I expect in a bash script.

python --version | grep --quiet 'Python 2.7.12 :: Continuum Analytics'
if [ $? == 0 ]; then
    echo "python version ok"
fi

But the grep command always returns 1, instead of 0, even when I get a good match, even with a simple grep 'Python'. To check it, echo "${PIPESTATUS[1]}" Returns 1

If I pipe some other output to grep, it works as expected, for instance:

echo 'Python 2.7.12 :: Continuum Analytics' | grep --quiet 'Python 2.7.12 :: Continuum Analytics'

This works properly, and echo "${PIPESTATUS[1]}" Returns 0

What is going wrong with the python --version command piped to grep? how can we fix it?

Lundy
  • 663
  • 5
  • 19
  • 2
    Replace `|` by `2>&1 |`. – Cyrus Oct 11 '16 at 15:26
  • @Cyrus that did the trick, but why? Also, what lead you from my issue, piping output to grep, to thinking about Redirecting stderr/stdout? – Lundy Oct 12 '16 at 16:08
  • For more information I suggest to take a look at: [Standard streams](https://en.wikipedia.org/wiki/Standard_streams) – Cyrus Oct 14 '16 at 17:04

1 Answers1

-1

Try using grep's -c, --count option;

count=$(python --version 2>&1 | grep -c 'Python 2.7.12 :: Continuum Analytics')
if [ $count == 1 ]; then
    echo "python version ok"
fi
CAB
  • 1,106
  • 9
  • 23