How to get only the version number of PHP using shell commands

PHPversion

I want to get only the version of php installed on CentOS.

Output of php -v

PHP 7.1.16 (cli) (built: Mar 28 2018 13:19:29) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies

I tried this following:

php -v | grep PHP | awk '{print $2}'

But the output I got was:

7.1.16
(c)

How can I get only 7.1.16?

Best Answer

On my system:

$> php -v | grep ^PHP | cut -d' ' -f2
7.0.32-0ubuntu0.16.04.1

as grep PHP matches every PHP string it encounters.

The ^PHP means "match only the string 'PHP' when it is at the start of a line".

Obviously, this works if the output format of php -v is consistent across versions/builds.

For reference, the whole output was:

PHP 7.0.32-0ubuntu0.16.04.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.32-0ubuntu0.16.04.1, Copyright (c) 1999-2017, by Zend Technologies
Related Question