« Back to home


Posted on

I wrote a quick script to preview a markdown file (or multiple) in Google Chrome from the command line. This is sometimes useful to me. Feel free to copy for your own use.


# Prerequisites: 
# (1) Install Google Chrome
# (2) Install markdown converter - I use this one for Github flavoured markdown: sudo npm install markdown-to-html -g

# Exit if no input file specified
if [ $# -eq 0 ]; then
    echo "preview-md: specify one or more .md files to preview."
    exit 1

# Chrome won't open a html file from stdin, so we can't just pipe into chrome. Create temporary files in this directory.

mkdir $TMPDIR

for filename in "$@"
    # Only process .md files, skip all others.
    if [ `echo $filename | grep '.md$'` ]; then
        # Get pathname and filename, so we can nest within the tmp directory if necessary.
        html_path=`dirname $filename`
        mkdir -p $TMPDIR/$html_path
        markdown $md_filename > $html_filename && google-chrome $html_filename &> /dev/null &

# Give chrome a little bit to start up and load the html files. Needs to scale with number of files.   
sleep $((2 + $#/2))

# On exit of this script, remove the directory containing the tmp files.
trap "rm -r $TMPDIR" EXIT

Assuming you saved the script in your $PATH as preview-md (and made it executable), you can call it as:

preview-md input.md

or with multiple input files:

preview-md input1.md input2.md

I wrote this script over a few hours this afternoon, and I’m mostly happy with it - except for the sleep command, specifically the sleep duration, which is frankly a hack. It’s necessary to avoid cleaning up the .tmp directory before Chrome is ready, but on a faster machine (I wrote this on a GPD Pocket - most machines are faster ;-)) the script will wait unnecessarily long to cleanup the temporary files after Chrome is done loading. On a slower system, on the other hand, it may not actually wait long enough for Chrome to finish loading. I may look into a better way to check if Chrome is done loading pages (I’m thinking that checking the output of top/ps may work).