Bash Script Fails Within Hazel

Get help. Get answers. Let others lend you a hand.

Moderator: Mr_Noodle

Bash Script Fails Within Hazel Mon Feb 03, 2025 12:47 pm • by tillemetry
Hello,

I have a Bash shell script that works fine when I run it from the command line with a proper path to the folder or file I'm trying to operate on. It changes a file's name based on the date found in its PDF text.

When I run it from the "Run shell script" in Hazel, it fails. When I run it using Preview Rule, it responds, "Rule Does Not Match."

I think it's a path error, but I also think I'm using 1 correctly. Can anyone help?

Here it is:

#!/bin/bash

# Function to process a single PDF
process_pdf() {
pdf_file="$1"

# Extract text from the PDF using pdftotext and clean up spaces and line breaks
text=$(pdftotext -layout "$pdf_file" - | tr '\n' ' ' | tr -s ' ')

# Search for "Pay Start Date" followed by a date in MM/DD/YYYY format
date_match=$(echo "$text" | grep -Eo 'Pay[[:space:]]*Start[[:space:]]*Date[[:space:]]*[0-1][0-9]/[0-3][0-9]/[0-9]{4}' | grep -Eo '[0-1][0-9]/[0-3][0-9]/[0-9]{4}' | head -n 1)

if [[ -z "$date_match" ]]; then
echo "No 'Pay Start Date' found in $pdf_file"
return
fi

# Convert MM/DD/YYYY to YYMMDD
month=${date_match:0:2}
day=${date_match:3:2}
year=${date_match:6:4}
formatted_date="${year:2:2}${month}${day}"

# Generate the new file name
dir=$(dirname "$pdf_file")
base=$(basename "$pdf_file" .pdf)
new_file="$dir/PayStub $formatted_date.pdf"

# Rename the file
mv "$pdf_file" "$new_file"
echo "Renamed $pdf_file to $new_file"
}

# Check if a folder or file was passed as an argument
if [[ -d "$1" ]]; then
# Process all PDF files in the folder
for pdf in "$1"/*.pdf; do
process_pdf "$pdf"
done
elif [[ -f "$1" ]]; then
# Process the single PDF file
process_pdf "$1"
else
echo "Usage: $0 /path/to/folder/or/pdf"
fi
tillemetry
 
Posts: 3
Joined: Wed Nov 13, 2024 6:18 pm

Re: Bash Script Fails Within Hazel Tue Feb 04, 2025 10:07 am • by Mr_Noodle
Do not assume any environment variables are set, including PATH. You should either specify that in the script or use full paths for everything.

If you turn on debug logging (https://www.noodlesoft.com/kb/hazel-debug-mode/), the logs will show the scripts output so you can print out debug information to help isolate the issue.
Mr_Noodle
Site Admin
 
Posts: 11865
Joined: Sun Sep 03, 2006 1:30 am
Location: New York City


Return to Support

cron