Ubuntu – How to run xrandr commands at startup in Ubuntu

command linedisplaydisplay-resolutionstartup-applicationsxrandr

How can I run the following xrandrcommand on startup?

xrandr

cvt 1368 768 
xrandr --newmode "1368x768_60.00"   85.25  1368 1440 1576 1784  768 771 781 798 -hsync +vsync
xrandr --addmode VGA1 1368x768_60.00
xrandr --output VGA1 --mode 1368x768_60.00 

Best Answer

  • Adding complicated commands to Startup Applications

    In General, you can add commands to run on start up (log in) by choosing: Dash > Startup Applications > Add. In this case, you have a complicated command to run.

    There are two options to do that:

    1. write a separate script:

      #!/bin/bash
      
      cvt 1368 768 
      # xrandr only works in X11 sessions, not Wayland
      [ "$XDG_SESSION_TYPE" = x11 ] || exit 0
      xrandr --newmode "1368x768_60.00"   85.25  1368 1440 1576 1784  768 771 781 798 -hsync +vsync
      xrandr --addmode VGA1 1368x768_60.00
      xrandr --output VGA1 --mode 1368x768_60.00
      

      Copy the script into an empty file, save it as set_monitor.sh and add the following command to startup applications as described above.

      /bin/bash /path/to/set_monitor.sh
      
    2. Chain the commands to one (very long) command:

       /bin/bash -c "cvt 1368 768&&xrandr --newmode "1368x768_60.00"   85.25  1368 1440 1576 1784  768 771 781 798 -hsync +vsync&&xrandr --addmode VGA1 1368x768_60.00&&xrandr --output VGA1 --mode 1368x768_60.00"
      

      In this case, using && between the commands will make each command run as soon (and if) the previous one is run succesfully, just like they are on separate lines.

      Then add the command to Startup Applications, as described above.

    Important note: adding xrandr commands to Startup Applications

    Adding xrandr commands to startup can be tricky; sometimes they break if they are run too early, before the desktop is fully loaded. Therefore you might (probably) need to add a little break into the command to (either) run the script or the command, like (in the last case):

    /bin/bash -c "sleep 15&&cvt 1368 768&&xrandr --newmode "1368x768_60.00"   85.25  1368 1440 1576 1784  768 771 781 798 -hsync +vsync&&xrandr --addmode VGA1 1368x768_60.00&&xrandr --output VGA1 --mode 1368x768_60.00"
    

    You might need to play a little with the sleep 15to find the optimal time.

    Note

    I left out the first line:

    xrandr
    

    since it does nothin but display some information on your screen setup :)