2

How can I display contents of bash script with syntax highlighting in iPython notebook?

My workflow usually consists of calling different bash scripts, and I would like to document the source code for these scripts in my notebook. My current solution is to make a bash cell and cat the script to have its contents display in the cell output. However, the script is not formatted and this is a bit cumbersome as well.

Example:

Code cell:

%%bash
cat myScript.sh

Output:

#! /bin/bash for i in {1..3}; do [ "$i" == "2" ] && echo "This is my bash script"; done

Desired output (with syntax highlighting):

#! /bin/bash
for i in {1..3}; do [ "$i" == "2" ] && echo "This is my bash script"; done
mlbendall
  • 23
  • 2

1 Answers1

1

You can use pygments in a similar fashion to this question. Here's an example:

def highlight_source_bash(filename):
    """For use inside an IPython notebook: given a filename, print the source code. Bash version."""

    from pygments import highlight
    from pygments.lexers import BashLexer
    from pygments.formatters import HtmlFormatter
    from IPython.core.display import HTML

    with open (filename, "r") as myfile:
        data = myfile.read()

    return HTML(highlight(data, BashLexer(), HtmlFormatter(full=True)))

Then calling highlight_source_bash('myScript.sh') should give the desired output.

Community
  • 1
  • 1
Ian
  • 1,483
  • 13
  • 14