This guide configures your laptop running Ubuntu 18.04.3 to do nothing when the lid closes while on AC power but suspend when on battery. Great for using your ThinkPad X1 Carbon or other laptops as a docked workstation without auto-sleep.
Edit /etc/systemd/logind.conf
and set the lid switch behavior:
sudo nano /etc/systemd/logind.conf
Add or edit these lines:
HandleLidSwitch=ignore HandleLidSwitchDocked=ignore
Restart logind:
sudo systemctl restart systemd-logind
This script dynamically changes the lid behavior depending on power state:
sudo nano /usr/local/bin/lid-power-handler.sh
#!/bin/bash LID_CONF="/etc/systemd/logind.conf" apply_setting() { local setting=$1 sudo sed -i "s/^HandleLidSwitch=.*/HandleLidSwitch=$setting/" $LID_CONF systemd-inhibit --what=handle-lid-switch --why="AC power override" --mode=block sleep 0 } while true; do if on_ac_power; then apply_setting "ignore" else apply_setting "suspend" fi sleep 10 done
Make it executable:
sudo chmod +x /usr/local/bin/lid-power-handler.sh
Set up a service so this script runs in the background:
sudo nano /etc/systemd/system/lid-power-handler.service
[Unit] Description=Dynamic Lid Close Behavior Based on Power State After=multi-user.target [Service] ExecStart=/usr/local/bin/lid-power-handler.sh Restart=always [Install] WantedBy=multi-user.target
Reload systemd and start the new service:
sudo systemctl daemon-reload sudo systemctl enable --now lid-power-handler.service