shell script to create a static HTML directory listing

tree -H . -o _includes/site-index.html should do everything you asked for.

There are some more options you might consider, like -T title. Refer to the XML/JSON/HTML OPTIONS section in the man page.


#!/bin/bash

ROOT=/tmp/test
HTTP="/"
OUTPUT="_includes/site-index.html" 

i=0
echo "<UL>" > $OUTPUT
for filepath in `find "$ROOT" -maxdepth 1 -mindepth 1 -type d| sort`; do
  path=`basename "$filepath"`
  echo "  <LI>$path</LI>" >> $OUTPUT
  echo "  <UL>" >> $OUTPUT
  for i in `find "$filepath" -maxdepth 1 -mindepth 1 -type f| sort`; do
    file=`basename "$i"`
    echo "    <LI><a href=\"/$path/$file\">$file</a></LI>" >> $OUTPUT
  done
  echo "  </UL>" >> $OUTPUT
done
echo "</UL>" >> $OUTPUT

My /tmp/test

/tmp/test
├── accidents
│   ├── accident2.gif
│   ├── accident3.gif
│   └── accident4.gif
├── bears
│   ├── bears1.gif
│   ├── bears2.gif
│   ├── bears3.gif
│   └── bears4.gif
└── cats
    ├── cats1.gif
    └── cats2.gif

The resulting output

<UL>
  <LI>accidents</LI>
  <UL>
    <LI><a href="/accidents/accident2.gif">accident2.gif</a></LI>
    <LI><a href="/accidents/accident3.gif">accident3.gif</a></LI>
    <LI><a href="/accidents/accident4.gif">accident4.gif</a></LI>
  </UL>
  <LI>bears</LI>
  <UL>
    <LI><a href="/bears/bears1.gif">bears1.gif</a></LI>
    <LI><a href="/bears/bears2.gif">bears2.gif</a></LI>
    <LI><a href="/bears/bears3.gif">bears3.gif</a></LI>
    <LI><a href="/bears/bears4.gif">bears4.gif</a></LI>
  </UL>
  <LI>cats</LI>
  <UL>
    <LI><a href="/cats/cats1.gif">cats1.gif</a></LI>
    <LI><a href="/cats/cats2.gif">cats2.gif</a></LI>
  </UL>
</UL>

You could expand the UL with href too, but I wasn't sure if that's what you wanted.

echo "  <UL><a href=\"/$path\">$path</a>" >> $OUTPUT

You would have to run this in the parent folder of _includes

Tags:

Shell

Bash