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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.