Bashlex: Bash Parser

0.18 · active · verified Thu Apr 09

Bashlex is a Python library providing a parser for bash commands. It can take a bash command string and convert it into an Abstract Syntax Tree (AST), allowing for programmatic inspection and manipulation of shell commands. The current version is 0.18, with releases occurring roughly annually or bi-annually.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing a bash command string using `bashlex.parse()` to obtain an AST, and `bashlex.tokenize()` to get all individual tokens including operators and comments. It shows how to inspect the structure and access parts of the parsed command.

import bashlex

command_string = "echo 'Hello World' && ls -l $HOME/#my-list.txt"

try:
    # Parse the command string into an Abstract Syntax Tree (AST)
    tree = bashlex.parse(command_string)

    print(f"Parsed command: {command_string}")
    print("--- AST Structure ---")
    for i, part in enumerate(tree):
        print(f"[{i}] Kind: {part.kind}, Value: {part.word if hasattr(part, 'word') else str(part)}")
        if hasattr(part, 'parts'):
            for p_sub in part.parts:
                print(f"  - Sub-part Kind: {p_sub.kind}, Word: {p_sub.word if hasattr(p_sub, 'word') else p_sub.value}")

    # Example: Tokenize the command to see all tokens, including comments and operators
    print("\n--- Tokens (including comments/operators) ---")
    tokens = bashlex.tokenize(command_string)
    for token in tokens:
        print(f"Token: '{token.word}', Pos: ({token.pos[0]},{token.pos[1]}), Kind: {token.kind}")

except bashlex.errors.BashlexError as e:
    print(f"Error parsing command: {e}")

view raw JSON →