How to Determine if LCD Monitor is Turned on From Linux Command Line

前端 未结 8 810
南方客
南方客 2021-01-31 04:04

How do you tell if a computer\'s monitor(s) are turned on/off from the command line in Linux? I\'ve traditionally thought of monitors as output-only devices, but I\'ve noticed t

8条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 04:28

    First, find the name of the display you want to inspect:

    xrandr -q
    

    Then change 'THE-MONITOR' to the proper name:

    #!/bin/sh    
    is_on="`xrandr -q | grep -A 1 'THE-MONITOR' | tail -1 | sed 's/[^\*]//g';`";
    

    Pipeline:

    • xrandr -q lists all monitors;
    • grep -A 1 'THE-MONITOR' filters to two lines, the one containing the name of your display, and the consecutive line, which will have an "*" next to it if the monitor is on;
    • tail -1 discards the first line;
    • sed 's/[^\*]//g' filter out everything but the "*";

    Now "$is_on" is a boolean string as "*" or empty.

    This will only work if your preferred mode is at the top of the mode list, which is very usual.

    The whole script for turning on and off:

    #!/bin/bash
    is_on="`xrandr | grep -A 1 'DVI-I-1' | tail -1 | sed 's/[^\*]//g';`";
    if [ "$is_on" ]
    then
        xrandr --output DVI-I-1 --off
    else
        xrandr --output DVI-I-1 --auto --left-of HDMI-0 
    fi
    

提交回复
热议问题