Created
December 27, 2024 14:47
-
-
Save npras/b3edc824cff76ce048c7b30a5a130094 to your computer and use it in GitHub Desktop.
Bash Script to Build a Static Website From a Bunch of Markdown Files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# set -euxo pipefail | |
set -euo pipefail | |
die() { | |
printf "%s\n" "$*" > "$(tty)" | |
exit 1 | |
} | |
get_title() { | |
(( $# == 1 )) || die "Usage: get_title \"some_file.md\"" | |
local pandoc_tmpl="tools/metadata.pandoc-tpl" | |
pandoc --template=$pandoc_tmpl "$1" | jq -r '.title' | |
} | |
build_html() { | |
(( $# == 2 )) || die "Usage: build_html \"input_file.md\" \"output_file.html\"" | |
local dir_layout="layout" | |
cat "$dir_layout/top.html" > "$2" | |
pandoc "$1" >> "$2" | |
cat "$dir_layout/bottom.html" >> "$2" | |
} | |
create_static_assets() { | |
(( $# == 1 )) || die "Usage: create_static_assets \"output_dirname\"" | |
local dir_assets="assets" | |
cp -r "$dir_assets"/css "$1" | |
cp -r "$dir_assets"/images "$1" | |
cp -r "$dir_assets"/as_is/* "$1" | |
} | |
replace_in_file() { | |
(( $# == 3 )) || die "Usage: replace_in_file \"::SOME_PTTRN::\" \"CONTENT\" \"file.txt\"" | |
sed -i '' "s/$1/$2/g" "$3" | |
} | |
main() { | |
local dir_posts="content/posts" | |
local dir_pages="content/pages" | |
local dir_output="_output" | |
[[ -d $dir_output ]] && rm -rf "$dir_output" | |
mkdir "$dir_output" | |
create_static_assets "$dir_output" | |
for input_file in "$dir_posts"/*.md "$dir_pages"/*.md; do | |
just_file=$(basename "$input_file" .md) | |
output_file="$dir_output/$just_file.html" | |
build_html "$input_file" "$output_file" | |
title=$(get_title "$input_file") | |
replace_in_file "::TITLE::" "$title" "$output_file" | |
done | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment