Creating blog articles through a CLI

23 February, 2024
by Mark Teisman

I've created this blog article through a CLI wizard, which asks for the data that all my blog posts need, and generates a file in the right location. Here's the script:

#!/bin/bash

# Function to prompt the user for input
function prompt_for_input() {
    read -p "$1: " input
    echo "$input"
}

# Function to validate resource choice
function get_resource() {
    local resource
    while true; do
        resource=$(prompt_for_input "Resource (shorts/blog)")
        if [[ "$resource" == "shorts" || "$resource" == "blog" ]]; then
            echo "$resource"
            break
        else
            echo "Invalid resource. Please choose 'shorts' or 'blog'."
        fi
    done
}

# Validate title length
function get_title() {
    local title
    while true; do
        title=$(prompt_for_input "Title")
        if [ ${#title} -le 255 ]; then
            echo "$title"
            break
        else
            echo "Error: Title must be 255 characters or less."
        fi
    done
}

# Prompt for the resource, filename, title, and content
resource=$(get_resource)
filename=$(prompt_for_input "Filename")
title=$(get_title)

# Prompt for the content (multiline)
echo "Enter the content (press Ctrl+D on an empty line to finish):"
content=""
while IFS= read -r line; do
    content+="$line"$'\n'
done

# Check if any input is empty
if [ -z "$resource" ] || [ -z "$filename" ] || [ -z "$title" ] || [ -z "$content" ]; then
    echo "Error: All fields must be filled."
    exit 1
fi

# Create the file and append the data
file_path="/Users/bla/playground/bla/content/${resource}/${filename}"
mkdir -p "$(dirname "$file_path")" # Ensure the directory exists
cat << EOF > "$file_path"
+++
title = "${title}"
date = $(date '+%Y-%m-%d')
+++

$content
EOF

echo "File created at $file_path"