Python-powered shell providing superset of Python with shell primitives for cross-platform command execution and automation.
Xonsh provides a comprehensive alias system for creating custom commands, function shortcuts, and command transformations. The alias system supports multiple types including function aliases, executable aliases, and partial evaluation aliases for complex command building.
from xonsh.aliases import Aliases
class Aliases(collections.abc.MutableMapping):
"""Container for xonsh aliases with dict-like interface."""
def __init__(self):
"""Initialize alias container."""
def __getitem__(self, key: str) -> object:
"""Get alias by name.
Parameters
----------
key : str
Alias name
Returns
-------
object
Alias object (FuncAlias, ExecAlias, etc.)
"""
def __setitem__(self, key: str, value) -> None:
"""Set alias.
Parameters
----------
key : str
Alias name
value : str, callable, or Alias object
Alias definition
"""
def __delitem__(self, key: str) -> None:
"""Delete alias by name.
Parameters
----------
key : str
Alias name to delete
"""
def register(self, name: str, func: callable = None, **kwargs):
"""Register a function as an alias.
Parameters
----------
name : str
Alias name
func : callable, optional
Function to register (can be used as decorator)
**kwargs
Additional alias configuration
Returns
-------
callable or None
Function (for decorator usage) or None
"""
# Global aliases instance
from xonsh.built_ins import XSH
aliases = XSH.aliases # Main aliases containerfrom xonsh.aliases import FuncAlias
class FuncAlias:
"""Alias that calls a Python function."""
def __init__(self, func: callable, name: str = None):
"""Create function alias.
Parameters
----------
func : callable
Function to wrap as alias
name : str, optional
Alias name (defaults to function name)
"""
def __call__(self, args: list[str], stdin=None, **kwargs):
"""Execute the alias function.
Parameters
----------
args : list[str]
Command line arguments
stdin : optional
Standard input stream
**kwargs
Additional execution context
Returns
-------
object
Function return value
"""
# Usage examples
def my_command(args, stdin=None):
"""Custom command implementation."""
print(f"Args: {args}")
return 0
# Create function alias
func_alias = FuncAlias(my_command, "mycmd")
aliases['mycmd'] = func_alias
# Direct assignment (automatic FuncAlias creation)
def greet(args, stdin=None):
name = args[0] if args else "World"
print(f"Hello, {name}!")
return 0
aliases['greet'] = greetfrom xonsh.aliases import ExecAlias
class ExecAlias:
"""Alias that executes a subprocess command."""
def __init__(self, command: str, name: str = None):
"""Create executable alias.
Parameters
----------
command : str
Shell command to execute
name : str, optional
Alias name
"""
def __call__(self, args: list[str], stdin=None, **kwargs):
"""Execute the command.
Parameters
----------
args : list[str]
Additional arguments to append
stdin : optional
Standard input stream
**kwargs
Execution context
Returns
-------
int
Command return code
"""
# Usage examples
# Simple command alias
aliases['ll'] = ExecAlias('ls -la')
# Command with dynamic arguments
aliases['gitlog'] = ExecAlias('git log --oneline')
# Using the alias
"""
In xonsh shell:
>>> ll # Executes: ls -la
>>> ll /tmp # Executes: ls -la /tmp
>>> gitlog -10 # Executes: git log --oneline -10
"""# String aliases automatically become ExecAlias instances
aliases['la'] = 'ls -la'
aliases['grep'] = 'grep --color=auto'
aliases['df'] = 'df -h'
# List-based aliases for complex commands
aliases['weather'] = ['curl', 'wttr.in']
aliases['myip'] = ['curl', 'ifconfig.me']
# Aliases with argument placeholders
aliases['mkcd'] = 'mkdir -p $arg0 && cd $arg0'from xonsh.aliases import (PartialEvalAlias0, PartialEvalAlias1,
PartialEvalAlias2, PartialEvalAlias3)
# Base class for partial evaluation
class PartialEvalAliasBase:
"""Base class for partial evaluation aliases."""
def __init__(self, template: str, name: str = None):
"""Create partial evaluation alias.
Parameters
----------
template : str
Template string with argument placeholders
name : str, optional
Alias name
"""
# Specific arity aliases
class PartialEvalAlias0(PartialEvalAliasBase):
"""Partial evaluation alias with 0 arguments."""
class PartialEvalAlias1(PartialEvalAliasBase):
"""Partial evaluation alias with 1 argument."""
class PartialEvalAlias2(PartialEvalAliasBase):
"""Partial evaluation alias with 2 arguments."""
# Usage examples
# Single argument partial evaluation
aliases['cdls'] = PartialEvalAlias1('cd $0 && ls')
# Multiple argument partial evaluation
aliases['copyto'] = PartialEvalAlias2('cp $0 $1')
# Usage in shell:
"""
>>> cdls /tmp # Executes: cd /tmp && ls
>>> copyto a.txt b.txt # Executes: cp a.txt b.txt
"""from xonsh.built_ins import XSH
def context_aware_alias(args, stdin=None):
"""Alias that behaves differently based on context."""
env = XSH.env
if env.get('DEBUG'):
print(f"Debug: executing with args {args}")
# Different behavior in different directories
import os
if '/test' in os.getcwd():
print("Running in test mode")
return 0 # Test version
else:
print("Running in normal mode")
return 0 # Normal version
aliases['smartcmd'] = context_aware_aliasdef git_smart_status(args, stdin=None):
"""Smart git status that adapts to repository state."""
import os
from xonsh.built_ins import subproc_captured_stdout
if not os.path.exists('.git'):
print("Not a git repository")
return 1
# Check for uncommitted changes
status = subproc_captured_stdout(['git', 'status', '--porcelain'])
if status.strip():
# Show detailed status if changes exist
return subproc_captured_stdout(['git', 'status', '--short'])
else:
# Show branch and commit info if clean
return subproc_captured_stdout(['git', 'log', '--oneline', '-1'])
aliases['gs'] = git_smart_statusfrom xonsh.aliases import Aliases
# Alias registration patterns
def register_development_aliases():
"""Register common development aliases."""
dev_aliases = {
'py': 'python',
'py3': 'python3',
'ipy': 'ipython',
'jn': 'jupyter notebook',
'jl': 'jupyter lab',
}
for name, command in dev_aliases.items():
aliases[name] = command
# Conditional alias registration
def register_git_aliases():
"""Register git aliases if git is available."""
from shutil import which
if which('git'):
git_aliases = {
'g': 'git',
'gs': 'git status',
'ga': 'git add',
'gc': 'git commit',
'gp': 'git push',
'gl': 'git log --oneline',
}
for name, command in git_aliases.items():
aliases[name] = command# List all aliases
all_aliases = dict(aliases)
# Check if alias exists
if 'myalias' in aliases:
print("Alias exists")
# Get alias type and details
alias_obj = aliases.get('ll')
if isinstance(alias_obj, ExecAlias):
print("Executable alias")
elif isinstance(alias_obj, FuncAlias):
print("Function alias")
# Alias information
def show_alias_info(name: str):
"""Display information about an alias."""
if name in aliases:
alias = aliases[name]
print(f"Alias '{name}': {type(alias).__name__}")
if hasattr(alias, '__doc__') and alias.__doc__:
print(f"Documentation: {alias.__doc__}")
else:
print(f"Alias '{name}' not found")from xonsh.built_ins import XSH
# Access aliases through XSH session
session_aliases = XSH.aliases
# Environment-based alias configuration
def setup_conditional_aliases():
"""Setup aliases based on environment."""
env = XSH.env
# OS-specific aliases
if env.get('XONSH_PLATFORM') == 'win32':
aliases['ls'] = 'dir'
aliases['cat'] = 'type'
# Role-specific aliases
if env.get('USER_ROLE') == 'developer':
register_development_aliases()
# Project-specific aliases
project_root = env.get('PROJECT_ROOT')
if project_root:
aliases['cdproj'] = f'cd {project_root}'# In .xonshrc file
def load_custom_aliases():
"""Load custom aliases at startup."""
# Personal aliases
aliases['ll'] = 'ls -la'
aliases['la'] = 'ls -la'
aliases['..'] = 'cd ..'
aliases['...'] = 'cd ../..'
# Function aliases
def mkcd(args, stdin=None):
"""Make directory and change to it."""
if not args:
print("Usage: mkcd <directory>")
return 1
import os
directory = args[0]
os.makedirs(directory, exist_ok=True)
os.chdir(directory)
return 0
aliases['mkcd'] = mkcd
# Load project-specific aliases if available
try:
# Example: load from project configuration file
import os
if os.path.exists('.xonsh_aliases'):
exec(open('.xonsh_aliases').read())
except Exception:
pass # No project-specific aliases
# Call at startup
load_custom_aliases()The alias system provides powerful command customization capabilities, enabling users to create shortcuts, automate common tasks, and build complex command transformations that integrate seamlessly with xonsh's Python-shell hybrid environment.
Install with Tessl CLI
npx tessl i tessl/pypi-xonsh