Tagbash

Using lockfile to create a semaphore in bash scripts

Sometimes you want to limit the number of times a script can run in parallel. You can do so by using lockfile (part of procmail). For example: want to make sure a script only has one instance? Simply add

lockfile -r 0 "<lock file name>" || exit 1

to the start of your script. Retry count, sleep time, etc are configurable. The -! flag inverts the exit status, making in possible to use lockfile as break conditions in a while loops with bash.

PDF to JPG using ImageMagick’s convert

…while dealing with alpha/transparency:

convert -verbose -density 150 -trim <input>[PAGE-RANGE] -quality 100 -sharpen 0x1.0 -background white -alpha remove <output>

pdf2jpg.sh, usage: pdf2jpg.sh <input> [page-range], page range starting at 0.

#!/bin/bash
INPUT=$1
PAGES=$2
ME=`basename "$0"`
if [[ ! -f "${INPUT}" ]]
then
	echo "Input not found"
	echo "Usage: ${ME} <pdf> [[pages]]"
	exit 1
fi
if [[ $(file --mime-type -b "${INPUT}") != "application/pdf" ]]
then
	echo "Input not a PDF"
	exit 1
fi
BASENAME="`basename "${INPUT}" .pdf`"
OUTPUT=$(mktemp -q -u "${BASENAME}.XXXXXXXXX")
convert -verbose -density 150 -trim "${INPUT}${PAGES}" -quality 100 -sharpen 0x1.0 -background white -alpha remove "${OUTPUT}-%03d.jpg"

Reconnect VPN on connection loss using NetworkManager’s nmcli

Find the <UUID> of your VPN connection using:

nmcli connection show

Using nmcli you can (re-)connect to your VPN by:

nmcli connection up uuid 

Checking every 10 seconds, if VPN is still up, and reconnect otherwise:

#!/bin/bash +x
UUID="<UUID>"
while (true)
do
        VPNCON=$(nmcli connection show --active | grep -i vpn | grep -i "${UUID}" | cut -f3 -d " ")
        if [[ $VPNCON != "${UUID}" ]] # Double check
        then
                nmcli connection up uuid "${UUID}"
        fi
        sleep 10
done