Bash script to lock screen on Linux

Endrit Qerreti

Endrit Qerreti

In this tutorial, we are going to write a bash script that will lock the screen on linux once you execute it.

The goal of this script is to simply lock the screen when you need, it basically acts like a switch but the difference is that you wont need to confirm anything when you run the script as it locks the screen right away.

Step 1 - Create is the name of the script, create this file by using touch command or simply a text editor software.

sudo touch

Step 2 - Write Bash script

Once you have created on your computer, now you need to copy the code below into the file that you created.


echo "locking screen in 3 seconds"
sleep 3 
lockscreen="dm-tool lock"
echo "screen locked" 

Note: We are using dm-tool on the script, dm-tool is a tool that comes with lightdm display manager, if you are using another display manager then dm-tool will not work, you must use lightdm as display manager on your system

Step 3 - Make executable

Next, you need to make executable so the script executes when you run it

chmod +x

Step 4 - Lock your screen

Now you can lock your screen by running the script


The script will run exactly after 3 seconds when you run the command above, you can customize it to your preference if you want the script to lock your computer screen instantly or waiting longer than 3 seconds.


A real life scenario for this script would be locking the screen when you are away from the computer using another device, from your phone for example.  

One way to achieve this would be installing a ssh server on the computer where you want to lock the screen, and then have the other device log into the ssh server and run the script.  

This should work fine when you are on the same network, but the problem is that you need to have a static IP to be able to run the script outside of local network. So how do we do this? I have something in mind and I think we can make it work..However, I'll need to test a lot of stuff first and hopefully I make it work, and if yes, then I'm going to publish the tutorial and the solution, so until then you can use the ssh method. Stay tuned!