shell脚本创建静态HTML目录列表

Joe*_*ier 12 bash shell

所以我正在创建一个GitHub Pages网站,列出我的jglovier/gifs repo 中的所有Gif.GH Pages仅运行静态HTML/CSS/JS或Jekyll,因此我无法使用apache目录列表或任何其他服务器生成的变体.

所以我想做的是在命令行上运行一个脚本,让它浏览目录的根目录,列出里面的所有文件(只有一层深度),然后输出到html ul > li > a结构,或类似的东西对此:

root/
|
??? accidents/
|   ??? accident2.gif
|   ??? accident3.gif
|   ??? accident4.gif
??? bears/
|   ??? bears1.gif
|   ??? bears2.gif
|   ??? bears3.gif
??? cats/
    ??? cat1.gif
    ??? cat2.gif
    ??? cat3.gif
Run Code Online (Sandbox Code Playgroud)

我希望href值是站点根相对路径(即构建时的href="/cats/cat.gif ), and I need it to output into_includes/site-index.html , which will get pulled into a Jekyll layout file that wraps around myindex.md file and generatesindex.html`.

发现这个非常相似的另一个问题,并试图为我的目的实现它的答案,但是我太过于自己完成它的shell n00b了.

Pet*_*oes 16

#!/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
Run Code Online (Sandbox Code Playgroud)

我的/ tmp /测试

/tmp/test
??? accidents
?   ??? accident2.gif
?   ??? accident3.gif
?   ??? accident4.gif
??? bears
?   ??? bears1.gif
?   ??? bears2.gif
?   ??? bears3.gif
?   ??? bears4.gif
??? cats
    ??? cats1.gif
    ??? cats2.gif
Run Code Online (Sandbox Code Playgroud)

结果输出

<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>
Run Code Online (Sandbox Code Playgroud)

您也可以使用href扩展UL,但我不确定这是否是您想要的.

echo "  <UL><a href=\"/$path\">$path</a>" >> $OUTPUT
Run Code Online (Sandbox Code Playgroud)

您必须在_includes的父文件夹中运行它


Nic*_*per 6

tree -H . -o _includes/site-index.html应该做你要求的一切。

您还可以考虑更多选项,例如-T title. 请参阅手册页中的XML/JSON/HTML OPTIONS部分。