How to lock the screen and put the computer to sleep in a 1-liner from the command line (could be assigned to an Ubuntu shortcut key)
Tested on Ubuntu 22.04.
This isn't an answer directly to the question, but it may help some people:
You can lock the screen and put the computer to sleep in a single command like this:
# lock the screen and put the computer to sleep
sudo true && gnome-screensaver-command -l && sudo pm-suspend
You can assign the above command to a shortcut key if you want to quickly put your computer to sleep.
After putting your computer to sleep with the command above, you can then wake up your computer and verify it went to sleep like this:
journalctl -n 1000 -e | grep "PM: suspend"
You'll see some suspend entries. Here's an example run and output for me. Check the timestamps to ensure this is for the suspend you just did:
$ journalctl -n 1000 -e | grep "PM: suspend"
Jun 25 23:07:02 gabriel-my-computer-name kernel: PM: suspend entry (s2idle)
Jun 25 23:07:17 gabriel-my-computer-name kernel: PM: suspend exit
Explanation of the first command above, and how it works:
sudo true prompts your user for a password to run sudo. Once you type in your sudo password, it gets temporarily cached. true is a dummy command to always pass. So, on to the next command.
gnome-screensaver-command -l runs as non-sudo, locking the screen for your user's session.
- Now that the screen is locked,
sudo pm-suspend runs to suspend the system. It uses your cached sudo password that you entered and which was cached a moment ago when you ran sudo true.
The trick is to use sudo true first, to cached your password, since obviously once the screen is locked, you cannot type the password, and gnome-screensaver-command -l must run as non sudo!
What not to do
Don't do this! It will freeze your computer and require a hard reboot where you have to hold down your power button:
# bad: this locks up your computer; freezes laptop!; requires hard reboot
sudo pm-suspend && gnome-screensaver-command -l
References
- Where I first learned about
sudo pm-suspend, and journalctl, in general: https://learnubuntumate.weebly.com/draining-battery.html
See also
- My shorter answer which references this one: How can I suspend/hibernate from command line?