Bash “Keep or Delete” script for PDFs

1 minute read

I recently discovered that I had over 100 PDFs in my “Downloads” directory and needed to determine which ones I wanted to keep. Instead of spending 10 minutes manually sorting them, I invested 20 minutes in writing a script to assist me.

The script iterates through all the provided arguments and performs the following steps for each file:

  1. It opens the file in preview mode using Evince (this can be easily customized).
  2. A prompt appears asking whether to keep the file.
  3. The viewer is then closed.
    This step posed a challenge since GDK apps tend to fork, making it insufficient to grab the child PID using $!. To overcome this, I utilized lsof to identify all processes that had the file open and terminated them.
  4. If the response is “N,” the file is sent to the trash.
    I opted for using gio trash since that’s the trash utility I have installed.

This script transformed a tedious chore into an enjoyable task.

The Script

#!/bin/bash
set -euo pipefail

function yes_or_no {
    while true; do
        read -p "$* [y/n]: " yn
        case $yn in
            [Yy]*) return 0  ;;
            [Nn]*) echo "Aborted" ; return  1 ;;
        esac
    done
}

function open {
  evince -w "$1" 2>/dev/null
}

function killviewer {
  lsof "$1" 2>/dev/null | awk 'NR==2 {print $2}' | xargs -r kill
}

function trash {
    gio trash "$1"
}

for INPUT in "$@"; do
  open "$INPUT" &
  KEEP="$(yes_or_no "Keep $INPUT?"; echo $?)";
  killviewer "$INPUT"
  if  [[ "$KEEP" == 0 ]];then
    echo "keeping"
  else
    echo "deleting"
    trash "$INPUT"
  fi
done