Setting up a screen capturing script in Linux
Microsoft Windows has evolved significantly from the days when pressing the “Print Screen” key simply copied the desktop image to the clipboard, requiring users to manually paste it into an image editor to save it. Today, Windows 10 offers the Snipping Tool and Snip & Sketch, providing various methods to capture parts of the screen. Despite having two tools for the same task, which indicates some unfinished business, Microsoft has streamlined the screenshot process.
Most Linux distributions now also come with robust screenshot tools. However, if you use a niche window manager that lacks this functionality or if your built-in tool stops working, you can still capture screenshots using some basic knowledge and a single tool, which may already be installed by default on your system.
This tutorial will explain how to set up a screenshot script in the i3 window manager.
What does this script do?
-
Pressing the Print Screen Key: Captures the entire screen and saves it to an image file in a specified location.
-
Pressing the Scroll Lock Key: Captures the screen, saves it, and then opens the saved image in an editor of your choice.
It is a common task to screen capture something, some video stream we’re watching perhaps. But before we post it online, we want to mark some interesting part of our screen with a circle, or point to it with an ugly-looking arrow. Instantly opening image editor is a lot more convenient than saving the image to disk, then manually navigating to the folder in which the image resides and opening it. If that’s not enough, we would usually need to use the ‘open with’ option if plain image viewer and not editor is set as the default program for executing images.
After pressing the Print Screen key, the script first checks the folder in which we save capture files if any already exist. If they do, it takes the number of the newest one (the one with biggest number), increments that number by one and saves our new screen capture with that number.
In other words, if you already have print-screen1.jpg and print-screen3.jpg (let’s assume 2 has been deleted in the meantime), the script will create print-screen4.jpg instead of substituting print-screen1.jpg, or creating print-screen2.jpg.
If there are no print-screen[num] files in folder, it creates print-screen1.jpg.
This is hands-down the best default behavior, as it retains chronology and prevents sometimes unwanted file loss.
Requirements
We will use Bash as our shell language and import from ImageMagick, a powerful image processing tool. ImageMagick is available in most system repositories and can be installed easily.
Either of the two programs is worth getting to know it if you deal with images a lot and feel like you could automate some of your tasks. IM has slightly more robust tools, GM can perform faster in some scenarios. We will work with IM’s import.
One example of its use is having *watch monitor a particular folder where we save memes (the most important images on anyone’s HDD). We can order ImageMagick tools to check if the maximum resolution is not bigger than something and, if it is, reduce it to a sensible maximum.
Next, the script could check if those meme files have a compression level higher than, let’s say, 90, and if they do, compress them to 90 to save disk space. Then, we could automatically move those files to our final meme directory.
This is a very basic example, but it already shows how useful this set of tools can be.
You will most likely find ImageMagick in your system repository. It is spelled imagemagick.
Code
Code explanation
Thanks to piping, we accomplish many tasks in our first actual line of code:
- ls -v - ‘ls’ lists files in specified directory, ‘-v’ makes sure numbers are sorted properly (with default sorting, for example, 100 is before 2… because 1 is smaller than 2. we do not want that!)
- grep - searches directory list for files/directories containing a string print-screen
- tail -n1 - ‘tail’ displays last lines of our result list, ‘-n1’ narrows it down to just last line, which we’ve made sure is the one with the biggest number
- grep -Po… - grep extracts single or double digit number from that filename (you can append a second ‘\d?’ if for some reason you can end up with 100+ files).
- (?=.png) - it is a lookahead, meaning we only look for digits which are immediately followed by ‘.png’.
That lookahead is a safety measure against directories that contain the string ‘print-screen’. The script may one day encounter such a directory, but it is not likely to encounter a directory named […]print-screen[num][maybenum].png[…].
Even if such a rare thing happens, the script will create a file with one number higher than the number in this directory, assuming there are no print-screen files with higher numbers. This is a rare worst-case scenario and still not hazardous.
The second line does arithmetic (which we enable with double parentheses). It adds one to append that number to the filename later. If you want a different numbering order, you can change it easily here.
Bash can take dynamic typing to extremes, as is the case here. If the previous line returns nothing (if there are no print-screen files in our folder, or the last sorted one has no digits followed by ‘.png’), the next line takes that nothing and converts it to something arithmetically viable, because it now sits inside double parentheses, which are used for arithmetic operations. Because there is no data (or false, or an empty string), that data is converted to 0 to make it viable in the world of mathematics. And 0+1 gives 1, saving us from writing our script in a more complicated way to ensure that if there are no print-screen files, a proper number for a new filename is still generated.
Notice the file extension in the second and fourth lines. Change it to any image format you want and test it to ensure that the import tool supports such a format.
The third line is where the magic happens. The import tool is told to capture the main display window with the -window root option.
Just like xwininfo, xprop, and many other useful X tools, import waits for a user click to specify the window for capture. But we don’t want to capture just one program window, but the entire screen, and we want it to happen automatically instead of requiring us to click each time. That’s why we have to be specific.
If you only have one monitor, you can safely remove the -crop 1920x1080+0+0 part. I have two monitors, the first one set to 1080p resolution. import with -window root captures content from all monitors into one glued-together image. I want to get the left-most monitor’s content only, so after capturing, I need to crop it to the position and dimensions of my first monitor.
That is why the script specifies geometry (you can read more about geometry in this article). Most people only have one monitor, and while the script will work for them as well, they won’t need that bit of code.
But because it’s there, it will also work for people with more than one monitor. If yours has a different resolution than 1920x1080, change those numbers. If you don’t want the left-most monitor’s contents, replace ‘+0+0’ with the proper starting pixel location.
Binding the script to a key
As mentioned at the start, if your window manager is not i3, search for how to add system-wide keyboard shortcuts in your Linux distribution/window manager.
Usually, you can set a key to execute a command. Instead of a system command, point to a file (with the full path, so the system knows where to look for it).
In i3, that operation is very simple. Edit this file: ~/.config/i3/config, and add these two lines:
bindsym Print exec /path/to/file.sh
bindsym Scroll_Lock exec “import -window root -crop 1920x1080+0+0 /location/to/save/image.jpg; pinta /location/to/save/image.jpg”
As far as I know, i3 can only execute single statement, so to execute two, we need to sneak them in as one command inside quotes.
Editing does not require automatic numbering of the following files. After all, we capture, edit, and save each time. Therefore, we only use the import command here and not the entire script. Be sure it is called with the exact same options and parameters as inside your script if you want to capture the same screen area.
The Print and Scroll Lock keys can be changed to any other ones you want. A list of popular names and how to easily get any key name you want that i3 understands can be found here.
Remember that binding a key or key combination directly in the window manager usually means no application can use it. Otherwise, one key could potentially execute multiple unrelated actions, leaving the user in a state of confusion.
Window managers execute instructions they have for the key and don’t send the signal further. Programs don’t even know that the key was pressed.
Final word
Setting up a screen capturing script in Linux can significantly enhance your productivity by automating and simplifying the process. With the right tools and a well-crafted script, you can easily capture high-quality recordings of your screen activities. This approach not only saves time but also ensures consistency and reliability in your screen captures.
Thank you for following along with this guide. I hope you found it helpful and that it empowers you to create effective screen recordings on your Linux system. Feel free to experiment with the script and tailor it to your specific needs. Happy capturing!