Search code examples
xonsh

Xonsh option mimicing bash -x flag


Is there something similar to the -x option for bash in xonsh to print every (shell) command as it runs?


Solution

  • You can set $XONSH_TRACE_SUBPROC = True to log every subprocess argument list, though it doesn't appear to expand aliases:

    >>> $XONSH_TRACE_SUBPROC = True
    >>> aliases["ls"] = "eza"
    >>> ls -l
    TRACE SUBPROC: (['ls', '-l'],), captured=hiddenobject
    

    If you want more complex logging, you can set $XONSH_TRACE_SUBPROC_FUNC to a custom callback, like this:

    >>> def tracer(cmds: tuple[list], captured: Union[bool, str] = False):
        # If you want to run any subcommands in this function, you'll have to disable tracing first in order to avoid recursion.
        $XONSH_TRACE_SUBPROC = False
        # Run `which` on the first argument of each command:
        expanded = [$(which @(cmd[0])).strip() for cmd in cmds]
        $XONSH_TRACE_SUBPROC = True
        print(f"TRACE SUBPROC: {cmds}, expand to {expanded}", file=sys.stderr)
    
    >>> $XONSH_TRACE_SUBPROC_FUNC = tracer
    >>> ls -l
    TRACE SUBPROC: (['ls', '-l'],), expand to ['eza]