Reading version from vmlinuz using file command

0

As the title says:

How to read vmlinuz version (directly) using file command?

Using: file /vmlinuz | grep version,
It must show like this 4.11.0-9.1-liquorix-amd64.

Daniel

Posted 2017-07-23T15:21:08.773

Reputation: 3

Answers

1

Initial note

My file -bL /vmlinuz returns:

Linux kernel x86 boot executable bzImage, version 3.2.0-4-amd64 (debian-kernel@lists.debian.org) #1 SMP Debian 3., RO-rootFS, swap_dev 0x2, Normal VGA

This knowledge may be useful if you need to adjust or debug what follows.


With grep

You used grep, that's why at first I assume you want it to be a crucial part of the solution.

file generates one line per its argument, grep works with entire lines so it seems like it's not a right tool here. There is, however, -o option which makes grep report only matched part of a line. This is non-POSIX in the first place so I don't really care about other parts of the following command being POSIX compliant.

The command is:

file -bL /vmlinuz | grep -o 'version [^ ]*' | cut -d ' ' -f 2

About file options: -L makes it follow symbolic links (/vmlinuz is often a symlink to /boot/vmlinuz-something), -b prevents it from printing the filename (because we don't need it anyway).

The interpretation of version [^ ]* is: literal version, then a literal space, then as many non-space characters as it can get. In your case the output will be version 4.11.0-9.1-liquorix-amd64.

Finally cut leaves only the second field, having a space as field delimiter. This should produce the output you need.


Without grep

The solution in quite simple form may be:

file -bL /vmlinuz | sed 's/.*version //;s/ .*//'

It replaces the parts you don't want with empty strings. If the file output has unexpected format (e.g. you didn't use -L while you should have), the output is non-empty yet invalid. Note the first solution (with grep) yields nothing in this case.

With some sed tricks we can patch this:

file -bL /vmlinuz | sed -n '/version /!q;s/.*version //;s/ .*//p'

In the above command sed silently quits when there's no version in its input. Now, if your sed supports this, you may want it to return exit status like this:

file -bL /vmlinuz | sed -n '/version /!q1;s/.*version //;s/ .*//p'

I consider this last command the best so far.

Kamil Maciorowski

Posted 2017-07-23T15:21:08.773

Reputation: 38 429