Turn your laptop screen off with a keyboard shortcut in Ubuntu Karmic
Back in the pre-Karmic days (or, the good ole’ days, as I call them) you could turn your laptop screen off by issuing this simple command:
xset dpms force off
I had a nice script set up and mapped to a keyboard shortcut to turn my screen off whenever I wanted (say if I was using my laptop to play music and wanted to save some battery life). In Karmic, however, a regression causes this command to turn your screen off only briefly. After a few seconds, your screen will turn back on, on its own. This might be an Intel-specific problem—I have the misfortune of having an Intel video card on my Ubuntu install—but I’m not sure.
To get around this problem, I created a slightly different (and slightly less ideal) script that turns the screen off when a shortcut key is pressed, and then turns it back on after they same key is pressed again. Here’s how to get it for your own laptop:
Create a new file using Nano. I put it in a directory called .scripts, you can put it wherever you like:
Paste the following into your new file using ctrl + shift + v:
#!/bin/bash screenOffLockFile=/tmp/screen-off-lock if [ -f $screenOffLockFile ]; then rm $screenOffLockFile notify-send "Screen on." -i /usr/share/icons/gnome/48x48/devices/display.png else touch $screenOffLockFile sleep .5 while [ -f $screenOffLockFile ] do xset dpms force off sleep 2 done xset dpms force on fi
(An explanation follows). Press ctrl + x to quit Nano, then y to save your script.
Make the script executable:
chmod +x ~/.scripts/screen-off
Open the System menu, go to Preferences, then Keyboard Shortcuts (or press alt + f2) and run gnome-keybinding-properties.
Click Add, enter ‘Turn Off Screen’ under Name and ~/.scripts/screen-off under Command.
After you’ve added the command, it will appear under the Custom Shortcuts header. Click on your new command to assign it a shortcut key of your choice (I use ctrl + alt + s).
And that’s it. Press your shortcut key to turn your screen off, and press the shortcut key again to turn it back on.
What the script does
When you first press the shortcut key with your screen on, the script checks if there’s a certain file in /tmp/. If it doesn’t find it, it’ll create it and then enter an infinite loop that turns your screen off every 2 seconds if the special file still exists (thus working around Karmic’s regression). When you press the shortcut key with your screen already off, it’ll delete the file and do nothing else, causing the first instance of the script to exit its infinite loop (since it no longer sees the special file) and turn your screen back on again.
It’s as simple as that. It’s not as ideal as the pre-Karmic solution, but it’ll have to do until Canonical QA gets their act together.