How to discover the screen resolution in Linux scripts

Configurare noua (How To)

Situatie

Solutie

Sometimes you need to know what your screen resolution is before your script launches an application or does some further processing. You may need to pass the resolution as command line parameters to the application you’re about to launch, or you may have reset the resolution and you want to check that the change of resolution was successful.

Lowering the resolution is a trick that can make playing some games on older, less powerful, hardware possible. Changing the resolution back and forth manually will soon get tiresome, so the obvious answer is to do it from within a script.

The commands we’re going to look at were installed as standard on all the distributions we checked, so there shouldn’t be a need to install anything. You can use these techniques straightaway, and your scripts should be portable across different distributions.

Using the xrandr Command

The xrandr command can be used to set and query the screen resolution. By default, with no parameters, it generates a list of video modes that are supported by your screen, or screens.

The preferred video modes are followed by a plus sign “+”, and the current video mode is followed by an asterisk “*”.

This screen has only one preferred video mode, and it happens to be the current video mode. Although you can have several preferred modes, there can only be one current mode. That means if we can find the line with the asterisk in it, we can determine what the current video mode settings are.

You might see online examples where this is what they do. They use grep to find the line with the asterisk in it, and then use sed or awk to parse out the information we’re interested.

But there is a simpler way. The information in the output from xrandr contains details of the “connected primary” screen, including the current video mode resolution. We can use awk to parse that out, without using grep at all.

xrandr | awk -F‘[ +]’ ‘/primary/{print $4}’

This is how it works. We use the -F (field separator) option to tell awk that spaces and plus signs “+” are to be treated as field delimiters. We’re searching for lines with the word “primary” in them. This word was picked because it appears in the line we’re interested in, and doesn’t appear anywhere else in the output from xrandr.

Splitting that line into fields at spaces and plus signs “+” means the current resolution is located in field four. We use the awk print command to print the fourth field. Because we’re also splitting the fields at plus signs, the “+0+0” is trimmed off the back of the resolution, becoming fields five and six. We’re not interested in those.

Tip solutie

Permanent

Voteaza

(2 din 4 persoane apreciaza acest articol)

Despre Autor