Scripted screen captures

This is a script I put together for capturing a window’s contents as it changes, because “Print Screen and crop” gets old very quickly!

It saves me a lot of time when working in virtual machines or creating user docs, as it means that every step (and error message) is captured.

The commands used are in the x11-utils and netpbm and x11-apps packages on Debian.

sudo apt-get install x11-utils netpbm x11-apps

capture.sh

#!/bin/bash
echo "Click a window to start capturing it."
window=`xwininfo -int | grep 'Window id:' | cut -d' ' -f4`
echo -n "Capturing window $window"
prev=""
i=1
empty=`echo -n "" | md5sum | cut -d' ' -f1`
captured="captured.txt"
echo -n "" > $captured
while [ "$prev" != "$empty" ]; do
	md5sum=`xwd -id $window 2> /dev/null | xwdtopnm 2> /dev/null | md5sum | cut -d' ' -f1`
	if grep -Fxq "$md5sum" "$captured"
	then
		echo -n "."
	else
		if [ "$md5sum" != "$empty" ]
		then
			echo $md5sum >> $captured
			echo ""
			echo -n $md5sum
			file=`date --iso`-capture-`printf "%03d" $i`.png
			xwd -id $window | xwdtopnm 2> /dev/null | pnmtopng 2> /dev/null > $file
			i=$[i+1]
		fi
	fi
	sleep 1
	prev=$md5sum
done
echo ""
echo "Empty screen capture received. Quitting. (did you close the window?)"

Example

If you wanted to document a “Malformed Expression” error in Gnome Calculator, you can run capture.sh and then demonstrate it:

$ ./capture.sh
Click a window to start capturing it.
Capturing window 31457283
3bbe32ef05f49ae65922fcfedc842828
c0cef7d3108263fbb1beaa7b52492e6a
fd6df04c4ad844bb4a2f27be29dffb29
6ba0fb7ee1ca85640998013c6a258520.
bb061cc56fa3822f9764c0f6af2156df
5f788568c7f34cda55a1680ac72e1cf0
dca714e6691a3a239914106996905047
0bf916ba3f96f3def57191174e55dea0.
2a4a2589662901d9a55d1e170ffbd322....
Empty screen capture received. Quitting. (did you close the window?)

The lines are checksums of PNM data, and the dots are times when no screenshot was saved. This guarantees that each file in the output is unique:


Example of captured files

The captured.txt file simply contains the list of checksums, and is useless after the script terminates.