I am trying to display the version number of a Linux distro on a web page. The distro is DietPi. The version number is stored in /DietPi/dietpi/.version and looks like this;
G_DIETPI_VERSION_CORE=7
G_DIETPI_VERSION_SUB=3
G_DIETPI_VERSION_RC=2
G_GITBRANCH='master'
G_GITOWNER='MichaIng'
This is what I have experimented with so far, which I’ve put together from examples I have found on SO.
<?php system("cat /DietPi/dietpi/.version | cut -f2 -d'=' | sed 's/[^0-9]*//g' ") ;?>
This works but there are spaces between the digits thus
7 3 2
and I need to add periods so it looks like this
7.3.2
I suspect the above is probably not the most efficient way of doing this. I’d welcome help on inserting the periods or ideas on simpler methods that would work for me.
4
Answers
A simple way to do it, using what you have done already, is to just replace the spaces with dots. You can use str_replace for that.
The laziest option would be
parse_ini_file
andextract
. (The usual caveat: do not use with arbitrary input. Seems perfectly reasonable in this case.)Then you have all entries available as vars for string concatenation right away:
If there are e.g. stray carriage returns, then applying
trim
might still be necessary. – Do anarray_map("trim", …)
before theextract()
.Typically parse_ini would already strip off trailing whitespace however.
@mario did beat me to it, but I had the same idea, this is my suggestion:
There is a shortcut that can be taken in this case as those are the first three values in that file:
your mileage my vary, its basically the same, I think the main benefit is using parse_ini_file over system.
(you may want to throw exceptions on warnings with this last variant to at least deal with problems getting the version number)
I believe DietPi already sources these values to your environment. If that’s the case, you can skip the file read/parse and just pull directly out of
$_ENV
. (I’m not 100% sure about this, but it’ll be a quick test for you at least.)