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 screenlock.sh
screenlock.sh is the name of the script, create this file by using touch command or simply a text editor software.
sudo touch screenlock.sh
Step 2 - Write Bash script
Once you have created screenlock.sh on your computer, now you need to copy the code below into the file that you created.
#!/bin/bash
echo "locking screen in 3 seconds"
sleep 3
lockscreen="dm-tool lock"
echo "screen locked"
$lockscreen
Step 3 - Make screenlock.sh executable
Next, you need to make screenlock.sh executable so the script executes when you run it
chmod +x screenlock.sh
Step 4 - Lock your screen
Now you can lock your screen by running the script
./screenlock.sh
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.
Conclusion
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!