5
\$\begingroup\$

I'm pretty new to bash scripting. I want a script that I can run in a directory that contains .md files, runs pandoc on them, and delivers the output to a sibling folder html, i.e. my folder structure is like this:

.
├── html
└── md

Here is what I have working, I just don't know if I'm following good practices or if there's a nicer / more readable way of doing what I'm doing.

#! /bin/bash
# run this from a folder containing markdown files
# it delivers html to the sibling html folder
if hash pandoc 2>/dev/null; then
 for file in ./*.md ; do
 echo Converting $file
 cat "$file" | pandoc -o "$(echo $file | sed 's/^./..\/html/' | sed 's/.md$/.html/')"
 done
else
 echo "I need pandoc installed"
fi
asked Nov 17, 2018 at 20:14
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$
  • UUOC . pandoc takes the input file name as an argument. echo $file | pandoc -o outfile is equivalent to pandoc -o outfile $file. One process invocation down.

  • UUOS (sed in this case). bash has very rich string transformation features built in. For example, ${file%md} (see Parameter expansion section of man bash) will strip the md suffix form the filename. So consider

    for file in *.md; do
     pandoc -o ../html/${file%md}html
    done
    

    Two more process invocations down.

  • If by any chance an .md filename contains funny characters (like whitespace), the substitution will produce unexpected results. It is safer to use double quotes, as in `"${....}".

PS: It might be beneficial to abandon the shell script altogether in favor of make, with a Makefile having a single stem rule

../html/%.html: %.md
 pandoc -o $@ $<
answered Nov 17, 2018 at 20:38
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Awesome thank you! My workplace actually has an award for UUOC, I think I'll need to apply for it :) \$\endgroup\$ Commented Nov 17, 2018 at 20:44
  • \$\begingroup\$ Thanks again for your help. My script has evolved a bit since I asked the original question. Interested to know if there's a nicer way to pass an optional parameter to pandoc. \$\endgroup\$ Commented Nov 17, 2018 at 20:51
  • 1
    \$\begingroup\$ If you've got a new version of the code it is time for a new code review. It is ok to open a new question on here with modified code. It is nice to link to the previous question too. \$\endgroup\$ Commented Nov 18, 2018 at 2:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.