3
\$\begingroup\$

I wrote a simple bash script in order to batch convert Markdown files via pandoc and it is working for me. But I have the feeling the code is dirty. Could you help me improve it?

#!/bin/bash
rm -r out; mkdir out
for f in src/*.md
do
 filename=$(basename "$f")
 filename="${filename%.*}"
 echo "Processing $filename"
 pandoc "$f" -o "out/$filename.epub"
 pandoc "$f" -o "out/$filename.pdf"
done
chicks
2,8593 gold badges18 silver badges30 bronze badges
asked Feb 21, 2020 at 21:12
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

overall and good stuff

This is pretty good. I definitely wouldn't call the code dirty. Good stuff:

  • The indentation is good
  • putting double quotes around variable substitutions is a best practice
  • using $() for command substitution is the best practice also
  • the #! is good
  • providing meaningful output to the user is nice
  • the variable names are ok

suggestions

  • I get putting rm -r out; mkdir out on one line sounds good because they're related, but it doesn't help the readability here. If you want to tie them together so that the mkdir doesn't run unless rm succeeds then you could do rm -r out && mkdir out. Otherwise I'd put them on two lines. Breaking up things with blank lines, as you've already done, is enough to make clear which things belong together.
  • for f in src/*.md certainly works most of the time, but will break if there's any white space in a filename. Fixing this involves using find. This answer is part of a duped question, but it may be a bit easier to follow.
  • Having f and filename as variables is a bit confusing. For something this short it is pretty harmless which is why I said they were ok above. If you want to tweak this f might make more sense as fullpath or fqfn. And filename might be better as basename or base.
  • add if ! which pandoc... near the top to catch if pandoc is missing.
if ! which pandoc > /dev/null; then
 echo you need pandoc
 exit 1
fi

further reading

answered Feb 21, 2020 at 23:42
\$\endgroup\$
2
  • \$\begingroup\$ "for f in src/*.md certainly works most of the time, but will break if there's any white space in a filename." -- nope, not true, this is perfectly fine! \$\endgroup\$ Commented Feb 22, 2020 at 6:56
  • \$\begingroup\$ Don't use which unless is also a buitlin to the shell that you're using. It does not know builtins, functions and alias. \$\endgroup\$ Commented Mar 6, 2020 at 9:33

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.