🔎 Search - simple bash script

📆 2025-12-05 17:20

Here's a simple bash script that searches files for keywords. I use this script to power the search on this gemini capsule.

You can test the search script from my blog or via the link below:

🔎 Search Sava.Rocks blog posts

Features

Be aware, if you want to use this script there are 2 things you should keep in mind:

❗ Make sure to adapt to your blog structure ❗

Code

And now, the script:

#!/bin/sh
SEARCH_DIR="./blog/"
MAX_RESULTS=50


# Everything after '?' in /search/?TERM is in QUERY_STRING
QUERY="$QUERY_STRING"

# Decode %20 etc. to spaces
QUERY=$(printf '%b' "$(echo "$QUERY" | sed 's/%/\\x/g')")

# If empty, prompt Gemini client
if [ -z "$QUERY" ]; then
    printf "10 What are you looking for?\r\n"
    exit 0
fi


# GREP MODE (fixed string, case-insensitive)

GREP_CMD="grep -liF"

printf "20 text/gemini\r\n"
printf "# πŸ•΅ Sava.Rocks - Search results for: %s\r\n" "$QUERY"
printf "\r\n"
printf "=> /search/ πŸ”Ž Start another search\r\n"

# SEARCH EXECUTION

RESULTS=$(find "$SEARCH_DIR" -mindepth 2 -type f -name "index.gmi" ! -path "$SEARCH_DIRindex.gmi" -print0 \
          | xargs -0 $GREP_CMD "$QUERY" 2>/dev/null \
          | head -n "$MAX_RESULTS")

[ -z "$RESULTS" ] && { printf "No results.\r\n"; exit 0; }
printf "## Results in Sava's blog posts:\r\n"
printf "\r\n"


# TITLE EXTRACTOR
# GET'S THE TEXT FROM THE FIRST LINE STARTING WITH #
get_title() {
    grep -m 1 '^#' "$1" | sed 's/^# *//'
}


# FORMAT RESULTS

printf '%s\n' "$RESULTS" | while IFS= read -r FILE || [ -n "$FILE" ]; do
    # Normalize the path so it’s relative to the current directory
    REL=$(printf '%s' "$FILE" | sed 's#^./##')
    BLOG_SLUG=$(printf "%s" "$REL" | sed -E 's#^blog/##' | sed -E 's#/index\.gmi$##')
    LINK="/blog/$BLOG_SLUG/"
    TITLE=$(get_title "$FILE")
    [ -z "$TITLE" ] && TITLE="$BLOG_SLUG"

    # First matching line as snippet (trim to 280 chars)
    SNIPPET=$(grep -i -m 1 -F "$QUERY" "$FILE" | cut -c1-280)

    printf "=> %s %s\r\n" "$LINK" "$TITLE" # RESULT LINK
    printf "> %s\r\n" "$SNIPPET" # RESULT SNIPPET
    printf "\r\n"
done
printf "\r\n"
printf "=> /blog/ 🚢 Back to my blog"
printf "\r\n"

Go ahead and add search to your gemini gemlog 🕵️.

🚶 Back to Fun Stuff