Extending Jeff Schaller's answer, skip the pipeline altogether and just ask for the internal constant representation:
$ php -r 'echo PHP_VERSION;'
7.1.15
You can extend this pattern to get more, or less, information:
$ php -r 'echo PHP_MAJOR_VERSION;'
7
See the PHP list of pre-defined constants for all available.
The major benefit: it doesn't rely on a defined output format of php -v
. Given it's about the same performance as a pipeline solution, then it seems a more robust choice.
If your objective is to test for the version, then you can also use this pattern. For example, this code will exit 0
if PHP >= 7, and 1
otherwise:
php -r 'exit((int)version_compare(PHP_VERSION, "7.0.0", "<"));'
For reference, here are timings for various test cases, ordered fastest first:
$ time for (( i=0; i<1000; i++ )); do php -v | awk '/^PHP [0-9]/ { print $2; }' >/dev/null; done
real 0m13.368s
user 0m8.064s
sys 0m4.036s
$ time for (( i=0; i<1000; i++ )); do php -r 'echo PHP_VERSION;' >/dev/null; done
real 0m13.624s
user 0m8.408s
sys 0m3.836s
$ time for (( i=0; i<1000; i++ )); do php -v | head -1 | cut -f2 -d' ' >/dev/null; done
real 0m13.942s
user 0m8.180s
sys 0m4.160s
... | head -1
or there might be better ways