Skip to content
Back to top
View this page
Edit this page

# Built-in Aliases

This page describes the xonsh built-in commands and aliases.

## Well-known commands

### `cd`

Changes the directory. If no directory is specified (i.e. if there are no arguments) then this changes to the current user’s home directory.

### `ls`

The `ls` command is aliased to `['ls', '--color=auto', '-v']` on Linux. On macOS, FreeBSD, and DragonFlyBSD it is instead aliased to `['ls', '-G']`. On NetBSD and OpenBSD no `ls` alias is defined.

### `grep`

The `grep` command is aliased to `['grep', '--color=auto']`.

### `timeit`

Runs timing study on arguments. Similar to IPython’s `%timeit` magic.

### `exit`, `quit`, `EOF`

The commands `exit`, `EOF` and `quit` all alias the same action, which is to leave xonsh in a safe manner. Typing `Ctrl-d` is the same as typing `EOF` and pressing enter.

`exit N` sets the shell’s exit code to `N` and stops the rest of the current script:

    @ xonsh -c 'echo 1; exit 42; echo 3'
    1
    @ @.lastcmd.rtn
    42

## Xonsh-specific Aliases

### `history`

Tools for dealing with xonsh history. See the history tutorial for more information all the history command and all of its sub-commands.

    usage: history [-h]
                   {show,id,file,info,pull,flush,off,on,clear,delete,erasedups,gc,transfer} ...

    Try 'history <command> --help' for more info

    options:
      -h, --help            show this help message and exit

    commands:
      {show,id,file,info,pull,flush,off,on,clear,delete,erasedups,gc,transfer}
        show                Display history of a session, default command
        id                  Display the current session id
        file                Display the current history filename
        info                Display information about the current history
        pull                Pull history from other parallel sessions.
        flush               Flush the current history to disk
        off                 History will not be saved for this session
        on                  History will be saved for the rest of the session (default)
        clear               One-time wipe of session history
        delete              Delete all commands matching a pattern
        erasedups           Remove duplicate commands, keeping only the latest occurrence of each
        gc                  Launches a new history garbage collector
        transfer            Transfer entries between history backends.

### `showcmd`

Displays how commands and arguments are evaluated. Use `-e` to expand aliases.

    @ showcmd echo The @('args') @(['list', 'is']) $(echo here) "and" --say="hello" to @([]) you
    ['echo', 'The', 'args', 'list', 'is', 'here', 'and', '--say="hello"', 'to', 'you']
    @ showcmd ls
    ls
    @ showcmd -e ls
    ['ls', '--group-directories-first', '-A', '--color']

### `xonfig`

Manages xonsh configuration information.

    usage: xonfig [-h] {info,web,wizard,styles,colors,tutorial} ...

    Manage xonsh configuration.

    options:
      -h, --help            show this help message and exit

    commands:
      {info,web,wizard,styles,colors,tutorial}
        info                Displays configuration information
        web                 Launch configurator in browser.
        wizard              Launch configurator in terminal
        styles              Prints available xonsh color styles
        colors              Preview color style
        tutorial            Launch tutorial in browser.

### `xontrib`

Manages xonsh extensions. More information is available at Extensions

### `xcontext`

    @ xcontext
    [Current xonsh session]
    xxonsh: /home/snail/.local/xonsh-env/bin/xonsh
    xpython: /home/snail/.local/xonsh-env/bin/python # Python 3.12.10
    xpip: /home/snail/.local/xonsh-env/bin/python -m pip

    [Current commands environment]
    xonsh: /home/snail/.local/xonsh-env/bin/xonsh
    python: /usr/bin/python # Python 3.11.6
    pip: /usr/bin/pip

    CONDA_DEFAULT_ENV: my-env

Report information about the current xonsh environment, including paths to the Python interpreter, pip, xonsh itself, and relevant environment variables.

By default, symlinks in the displayed paths are resolved to their real targets; pass `--no-resolve` (`-n`) to show the raw paths instead.

### `xpip`

Runs the `pip` package manager for xonsh itself. Useful for installations where xonsh is in an isolated environment (e.g. conda, mamba, homebrew).

    @ which pip
    /usr/bin/pip  # system pip
    @ which xpip
    /home/snail/.local/xonsh-env/bin/python -m pip  # current xonsh session pip
    @ xpip install fire
    @ import fire
    @ fire
    <module 'fire' from '/home/snail/.local/xonsh-env/lib/python3.11/site-packages/fire/__init__.py'>

### `xpython`

Alias to the Python interpreter that is currently running xonsh (`sys.executable`). This is useful for running Python modules or scripts in the same environment as the shell itself, especially in complex setups like AppImage.

    @ python -V
    Python 3.12.10
    @ xpython -V
    Python 3.11.9
    @ which python
    /opt/homebrew/bin/python
    @ which xpython
    /home/snail/.local/xonsh-env/bin/python

### `xxonsh`

Launches exactly the same `xonsh` that was used to start the current session.

See Launching the Same Xonsh (xxonsh) for a worked example of using it as a building block to launch `tmux` with this exact xonsh (the `xtmux` recipe).

Mnemonic: think of the initial ‘x’ as ‘c’—xxonsh stands for (c)urrent xonsh.

### `xreset`

Clean the xonsh context. All user variables will be deleted.

### `trace`

Provides an interface to printing lines of source code prior to their execution.

    usage: trace [-h] {on,start,add,off,stop,del,rm,color,ls} ...

    Tool for tracing xonsh code as it runs.

    options:
      -h, --help            show this help message and exit

    commands:
      {on,start,add,off,stop,del,rm,color,ls}
        on (start, add)     begins tracing selected files.
        off (stop, del, rm)
                            removes selected files fom tracing.
        color (ls)          output color management for tracer

### `exec` and `xexec`

    usage: xexec [-h] [-l] [-c] [-a NAME] ...

    exec (also aliased as xexec) uses the os.execvpe() function to
    replace the xonsh process with the specified program.

    This provides the functionality of the bash 'exec' builtin::

        >>> exec bash -l -i
        bash $

    positional arguments:
      command          program to launch along its arguments

    options:
      -h, --help       show this help message and exit
      -l, --login      the shell places a dash at the
                       beginning of the zeroth argument passed to command to simulate login
                       shell.
      -c, --clean      causes command to be executed with an empty environment.
      -a, --name NAME  the shell passes name as the zeroth argument
                       to the executed command.

    Notes
    -----
    This command **is not** the same as the Python builtin function
    exec(). That function is for running Python code. This command,
    which shares the same name as the sh-lang statement, is for launching
    a command directly in the same process. In the event of a name conflict,
    please use the xexec command directly or dive into subprocess mode
    explicitly with ![exec command]. For more details, please see
    http://xon.sh/faq.html#exec.

## Command Decorators

### `@error_raise` and `@error_ignore`

Use `@error_raise` to raise an exception if the command returns a non-zero exit code — similar to `$XONSH_SUBPROC_CMD_RAISE_ERROR` but scoped to a single command, and it raises unconditionally (even inside `&&`/`||` chains and even when `$XONSH_SUBPROC_RAISE_ERROR` is disabled). Use `@error_ignore` to explicitly suppress the raise — it also wins over the chain-result check performed by `$XONSH_SUBPROC_RAISE_ERROR`.

    @ r = !(@error_raise ls nonono)
    subprocess.CalledProcessError: Command '['@error_raise', 'ls', 'nonono']' returned non-zero exit status 1.

    @ r = !(@error_ignore ls nonono)

### `@thread` and `@unthread`

Use `@thread` and `@unthread` to run command as threadable or unthreadable e.g to have a result of SSH command:

    @ !(@thread ssh host -T "echo 1")

### `@path` and `@paths`

Use `@path` and `@paths` to get Path object(s) from the command output.

    @ dir = $(@path echo '/bin')
      dir.exists()
    @ dirs = $(@paths echo '/bin\n/etc')
      [p.exists() for p in dirs]

### `@lines`

Return output as list of lines.

    @ lines = $(@lines cat file)

### `@json`

Parses JSON and returns a JSON object.

    @ data = $(@json curl https://example.com/data.json)

### `@jsonl`

Parses JSON lines and returns a list of JSON objects.

    @ items = $(@jsonl cat data.jsonl)

### `@yaml`

Parses YAML and returns a dict.

    @ config = $(@yaml cat config.yaml)

### `@toml`

Parses TOML and returns a dict.

    @ config = $(@toml cat pyproject.toml)

### `@xml`

Parses XML and returns an `xml.etree.ElementTree.Element`. Navigate it with `.tag`, `.attrib`, `.text`, `.find()`, `.findall()`, etc.

    @ feed = $(@xml curl -s https://github.com/xonsh/xonsh/releases.atom)
      ns = {'a': 'http://www.w3.org/2005/Atom'}
      [e.find('a:title', ns).text for e in feed.findall('a:entry', ns)[:5]]
    ['v0.23.6', 'v0.23.5', 'v0.23.4', 'v0.23.3', 'v0.23.2']

### `@lxml`

Parses XML with lxml and returns an `lxml.etree._Element`. Adds full XPath, richer error messages, and faster parsing on top of the stdlib `@xml`. Registered only when `lxml` is installed (`xpip install lxml`).

    @ feed = $(@lxml curl -s https://github.com/xonsh/xonsh/releases.atom)
      ns = {'a': 'http://www.w3.org/2005/Atom'}
      feed.xpath('//a:entry/a:title/text()', namespaces=ns)[:5]
    ['v0.23.6', 'v0.23.5', 'v0.23.4', 'v0.23.3', 'v0.23.2']

## Directory Stack

### `pushd`

Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the current working directory.

    usage: pushd [-h] [-n] [-q] [+N|-N|dir]

    Adds a directory to the top of the directory stack, or rotates the stack,
    making the new top of the stack the current working directory.

    On Windows, if the path is a UNC path (begins with `\\<server>\<share>`) and if the `DisableUNCCheck` registry
    value is not enabled, creates a temporary mapped drive letter and sets the working directory there, emulating
    behavior of `PUSHD` in `CMD.EXE`

    positional arguments:
      +N|-N|dir    * dir :
                       Makes dir be the top of the stack,
                       making it the new current directory as if it had been supplied as an argument to the cd builtin.
                   * +N :
                       Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero)
                       to the top of the list by rotating the stack.
                   * -N :
                       Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero)
                       to the top of the list by rotating the stack.

    options:
      -h, --help   show this help message and exit
      -n, --cd     Suppresses the normal change of directory when adding directories to the stack,
                   so that only the stack is manipulated.
      -q, --quiet  Do not call dirs, regardless of $PUSHD_SILENT

### `popd`

Removes entries from the directory stack.

    usage: popd [-h] [-n] [-q] [+N|-N]

    When no arguments are given, popd removes the top directory from the stack
    and performs a cd to the new top directory.
    The elements are numbered from 0 starting at the first directory listed with ``dirs``;
    that is, popd is equivalent to popd +0.

    positional arguments:
      +N|-N        Removes the Nth directory (counting from the left/right of the list printed by dirs w.r.t. -/+ prefix),
                   starting with zero.

    options:
      -h, --help   show this help message and exit
      -n, --cd     Suppresses the normal change of directory when removing directories from the stack,
                   so that only the stack is manipulated.
      -q, --quiet  Do not call dirs, regardless of $PUSHD_SILENT

### `dirs`

Displays the list of currently remembered directories. Can also be used to clear the directory stack.

    usage: dirs [-h] [-c] [-p] [-v] [-l] [N]

    Manage the list of currently remembered directories.

    positional arguments:
      N           Displays the Nth directory (counting from the left/right according to +/x prefix respectively),
                  starting with zero

    options:
      -h, --help  show this help message and exit
      -c          Clears the directory stack by deleting all of the entries.
      -p          Print the directory stack with one entry per line.
      -v          Print the directory stack with one entry per line,
                  prefixing each entry with its index in the stack.
      -l          Produces a longer listing; the default listing format
                  uses a tilde to denote the home directory.

## Jobs

### `jobs`

Display a list of all current jobs.

### `fg`

Bring the currently active job to the foreground, or, if a single number is given as an argument, bring that job to the foreground.

### `bg`

Resume execution of the currently active job in the background, or, if a single number is given as an argument, resume that job in the background.

### `disown`

The behavior of this command matches the behavior of zsh’s disown command which is as follows:

Remove the specified jobs from the job table; the shell will no longer report their status, and will not complain if you try to exit an interactive shell with them running or stopped. If no job is specified, disown the current job. If the jobs are currently stopped and the $AUTO_CONTINUE option is set ($AUTO_CONTINUE = True), a warning is printed containing information about how to make them running after they have been disowned. If one of the latter two forms is used, the jobs will automatically be made running, independent of the setting of the $AUTO_CONTINUE option.

## Source Aliases

### `source`

Executes the contents of the provided files in the current context. This, of course, only works on xonsh and Python files (`*.xsh`, `*.py`). Use `-e` to ignore extension.

### `source-foreign`

Like the `source` command but for files in foreign (non-xonsh) languages. It will pick up the environment and any aliases.

Supported shells: `bash`, `zsh`, `sh` (also `dash`, `ash`, `ksh`, `mksh`, `pdksh`), and `cmd` on Windows. Absolute paths like `/bin/bash` or `/bin/sh` are canonicalised to the same defaults.

The convenience wrappers below pre-set the `shell` and `--sourcer` arguments for the most common cases — every flag accepted by `source-foreign` is available on them as well.

    usage: source-foreign [-h] [-i] [-l] [--envcmd ENVCMD] [--aliascmd ALIASCMD]
                          [--extra-args EXTRA_ARGS] [-u] [-p PREVCMD]
                          [--postcmd POSTCMD] [--funcscmd FUNCSCMD]
                          [--sourcer SOURCER] [--use-tmpfile]
                          [--seterrprevcmd SETERRPREVCMD]
                          [--seterrpostcmd SETERRPOSTCMD] [--overwrite-aliases]
                          [--suppress-skip-message] [--show] [--show-output] [-d]
                          [-n]
                          shell files_or_code [files_or_code ...]

    Sources a file written in a foreign shell language.

    positional arguments:
      shell                 Name or path to the foreign shell
      files_or_code         file paths to source or code in the target language.

    options:
      -h, --help            show this help message and exit
      -i, --interactive     whether the sourced shell should be interactive
      -l, --login           whether the sourced shell should be login
      --envcmd ENVCMD       command to print environment
      --aliascmd ALIASCMD   command to print aliases
      --extra-args EXTRA_ARGS
                            extra arguments needed to run the shell
      -u, --unsafe          whether the source shell should be run safely, and not raise any errors, even if they occur.
      -p, --prevcmd PREVCMD
                            command(s) to run before any other commands, replaces traditional source.
      --postcmd POSTCMD     command(s) to run after all other commands
      --funcscmd FUNCSCMD   code to find locations of all native functions in the shell language.
      --sourcer SOURCER     the source command in the target shell language.
                            If this is not set, a default value will attempt to be
                            looked up based on the shell name.
      --use-tmpfile         whether the commands for source shell should be written to a temporary file.
      --seterrprevcmd SETERRPREVCMD
                            command(s) to set exit-on-error before any other commands.
      --seterrpostcmd SETERRPOSTCMD
                            command(s) to set exit-on-error after all other commands.
      --overwrite-aliases   flag for whether or not sourced aliases should replace the current xonsh aliases.
      --suppress-skip-message
                            flag for whether or not skip messages should be suppressed.
      --show                show the generated shell command that will be sent to the foreign
                            shell (does not show what the sourced script prints — see
                            ``--show-output`` for that).
      --show-output         forward stdout and stderr produced by the sourced script to the
                            xonsh terminal. By default they are silently discarded.
      -d, --dry-run         Will not actually source the file.
      -n, --non-interactive
                            Deprecated: The default mode runs in non-interactive mode.

#### `source-sh`

Thin wrapper around `source-foreign sh` with `--sourcer .` (the POSIX dot builtin, since `/bin/sh` on dash-based distros does not understand `source`). Use this to source `/etc/profile` and similar POSIX configuration files. Also covers `dash`, `ash`, `ksh`, `mksh`, and `pdksh` (env and aliases are picked up; shell-specific function listing is not).

#### `source-bash`

Thin wrapper around `source-foreign bash` with `--sourcer source`.

#### `source-zsh`

Thin wrapper around `source-foreign zsh` with `--sourcer source`.

## Windows Aliases

### cmd-based Aliases

The following aliases on Windows are expanded to `['cmd', '/c', alias]`:

    {'cls': ['cmd', '/c', 'cls'],
     'copy': ['cmd', '/c', 'copy'],
     'del': ['cmd', '/c', 'del'],
     'dir': ['cmd', '/c', 'dir'],
     'erase': ['cmd', '/c', 'erase'],
     'md': ['cmd', '/c', 'md'],
     'mkdir': ['cmd', '/c', 'mkdir'],
     'mklink': ['cmd', '/c', 'mklink'],
     'move': ['cmd', '/c', 'move'],
     'rd': ['cmd', '/c', 'rd'],
     'ren': ['cmd', '/c', 'ren'],
     'rename': ['cmd', '/c', 'rename'],
     'rmdir': ['cmd', '/c', 'rmdir'],
     'time': ['cmd', '/c', 'time'],
     'type': ['cmd', '/c', 'type'],
     'vol': ['cmd', '/c', 'vol'],
     }

### `activate`/`deactivate` on Windows with Anaconda

On Windows with an Anaconda Python distribution, `activate` and `deactivate` are aliased to `['source-cmd', 'activate.bat']` and `['source-cmd', 'deactivate.bat']`. This makes it possible to use the same commands to activate/deactivate conda environments as in cmd.exe.

### `sudo` on Windows

On Windows, if no executables named `sudo` are found, Xonsh adds a `sudo` alias that poly fills the “run as Admin” behavior with the help of `ShellExecuteEx` and `ctypes`. It doesn’t support any actual `sudo` parameters and just takes the command to run.

## User Aliases with Descriptions

Every alias can carry a one-line description. It surfaces in the tab-completion dropdown next to the alias name, and in the `cmd?` / `cmd??` help output.

For callable aliases, the function’s docstring is used automatically:

    @ @aliases.register('qwe')
      def _qwe():
          """List files in long format."""
          ls -la

    @ qw<TAB>
    qwe  List files in long format.

For string and list aliases — which have nowhere to attach a docstring — use the dict form:

    @ aliases['qwe'] = {'alias': 'ls -la', 'doc': 'List files'}
    @ aliases |= {
          'psg':  {'alias': ['ps', 'aux'], 'doc': 'Process list'},
          'g':    {'alias': 'git',         'doc': 'Git wrapper'},
      }

The dict form recognises two keys: `'alias'` (required, the alias value itself — string, list, or callable) and `'doc'` (optional, the one-line description). Other keys are reserved for future use and currently ignored.

When `'doc'` is set on a callable alias, it overrides the function’s own `__doc__` — handy for showing a shorter summary in completions while keeping a longer docstring in the source:

    @ def _bar():
          """Long, detailed description of bar..."""
          echo bar
    @ aliases['bar'] = {'alias': _bar, 'doc': 'Short summary'}
    @ ba<TAB>
    bar  Short summary

Reassigning an alias without a `'doc'` clears the previous description, so descriptions never accidentally stick to a different value bound under the same name.

By default, the description shows in the dropdown only when the alias has a docstring (or an explicit `'doc'`). To also show the binary path for non-alias commands, set `$CMD_COMPLETIONS_SHOW_DESC = True`.

## See also

- Callable Aliases – writing callable aliases in depth

- Subprocess – subprocess operators and capturing modes

- xonsh RC – defining aliases in RC files