Introduction
Hash is a POSIX shell written from scratch in C for Linux, macOS and BSD: one small binary with no dependencies beyond libc, and the comforts people install plugins for (syntax highlighting, autosuggestions, a git-aware prompt, did-you-mean, smart completion) built in.
184 of 186 smoosh POSIX tests pass, 1 skipped on purpose (why), 1 failing.
CI measured this on commit f085908 on 2026-11-11 (the run).
Why hash has the longer answer, a feature table against bash, dash, zsh and fish, and how the shell is tested.
Features
- POSIX Compliance - Works with existing shell scripts and POSIX-standard features
- Interactive Editing - Full line editing with cursor navigation, history, and tab completion
- Customizable Prompt - Git integration, colors, and flexible PS1 escape sequences
- Scripting Support - Variables, control structures, functions, and command substitution
- Modern Conveniences - Syntax highlighting, autosuggestions, and configurable colors
Quick Start
# Install on macOS
brew install juliojimenez/hash/hash-shell
# Install on Debian/Ubuntu
echo "deb [trusted=yes] https://hash-shell.org/apt/ stable main" | sudo tee /etc/apt/sources.list.d/hash-shell.list
sudo apt update && sudo apt install hash-shell
# Run hash
hash-shell
Command Line Options
| Option | Description |
|---|---|
-c string | Execute commands from string |
-i | Force interactive mode |
-l, --login | Run as a login shell |
-s | Read commands from standard input |
-v, --version | Print version information |
-h, --help | Show help message |
Example Session
$ hash-shell
hash v54
Type 'exit' to quit
#> echo "Hello, World!"
Hello, World!
#> for i in 1 2 3; do echo "Number: $i"; done
Number: 1
Number: 2
Number: 3
#> exit
Getting Help
- Documentation: You’re reading it!
- Issues: GitHub Issues
- Discussions: GitHub Discussions
License
Hash is open source software licensed under the Apache 2.0 License.
Continue to Installation to get started.
Why hash
hash is a POSIX shell written from scratch in C, in one binary that needs
nothing but libc. It runs the scripts you already have, and it brings the
things people install plugins for into the shell itself: syntax highlighting as
you type, autosuggestions from your history, a prompt that knows about git,
suggestions when a command name is misspelt, and completion that understands
cd, git, make and man.
It runs POSIX scripts
184 of 186 smoosh POSIX tests pass, 1 skipped on purpose (why), 1 failing.
CI measured this on commit f085908 on 2026-11-11 (the run).
smoosh is a test suite for POSIX shells
built from the standard and from bugs reported on the shells’ mailing lists;
it is what hash is measured against on every push, and the figure above is
rewritten from the latest run each time the site is published. Bugs it has
caught, from arithmetic on special parameters to the exit status of an EXIT
trap, are fixed in the shell, not worked around in the tests.
A test that still fails stays in the count and gets an issue under the
posix label;
the one skipped test is skipped for a documented reason, linked above.
A second suite, modernish, runs every week; the shell bugs it still finds are tracked openly.
What is built in
| hash | bash | dash | zsh | fish | |
|---|---|---|---|---|---|
Runs POSIX sh scripts | yes | yes | yes | in sh emulation | no |
| Syntax highlighting as you type | built in | no | no | plugin | built in |
| Autosuggestions from history | built in | no | no | plugin | built in |
| Git branch and status in the prompt | built in, with presets | scripts | no | vcs_info or plugin | built in |
| “Did you mean” for a misspelt command | built in | handler script | no | setopt correct | built in |
Completion for git, make, man, variables | built in | bash-completion package | no | compsys | built in |
| Programmable completion | complete -W, -F | complete | no | compsys | complete |
| Vi editing mode | yes | yes | no | yes | yes |
| Dependencies beyond libc | none | readline, ncurses | none | ncurses | several |
“plugin”, “package”, “handler” and “scripts” mean the shell can get the feature from something you add. hash ships it. The other shells are described as they are installed by their packages; some are more capable in other ways, and dash is smaller.
Size
The macOS Apple Silicon binary of the latest release is 261 KB; the static
Linux x86_64 binary, with libc inside it, is 1.4 MB
(release assets). It
starts in a few milliseconds and reads no configuration beyond ~/.hashrc.
How it is tested
Every push runs, on GitHub Actions, where you can read the results:
- the unit tests, the integration script and a pseudo-terminal harness that types at a real prompt, on Linux, macOS and FreeBSD, with gcc and clang (Tests);
- the 186 smoosh conformance tests (POSIX Compliance);
- AddressSanitizer, UndefinedBehaviorSanitizer, ThreadSanitizer, MemorySanitizer and Valgrind over the tests, and AFL++ fuzzing of the tokenizer, the parser, variable expansion and the string helpers (Sanitizers & Fuzzing).
Only the latest release is supported, and a security fix ships as a new release (security policy).
Try it
brew install juliojimenez/hash/hash-shell # macOS
sudo apt install hash-shell # Debian and Ubuntu, after adding the repository
docker run -it juliojimenez/hash-shell # anywhere with Docker
The installation pages have the APT repository line,
the FreeBSD binaries and the build from source. Nothing changes until you make
it your login shell; hash-shell runs it as a command like any other.
Installation Overview
Hash can be installed on Linux, macOS, and FreeBSD through various methods.
Quick Install
| Platform | Method | Command |
|---|---|---|
| macOS | Homebrew | brew install juliojimenez/hash/hash-shell |
| Debian/Ubuntu | APT | See APT instructions |
| All platforms | From source | make && sudo make install |
| Docker | Pull image | docker pull juliojimenez/hash-shell |
Choose Your Installation Method
- Linux - Binary releases for x86_64 and ARM64
- macOS - Homebrew or binary release
- FreeBSD - Binary release or ports
- APT Repository - Debian/Ubuntu with automatic updates
- Docker - Containerized hash shell
- From Source - Build from source code
System Requirements
- 64-bit operating system (x86_64 or ARM64)
- Linux kernel 3.2+ / macOS 10.15+ / FreeBSD 12+
- libc (glibc on Linux, system libc on macOS/BSD)
- Terminal with ANSI color support (optional, for colored output)
Verify Installation
After installation, verify hash is working:
hash-shell --version
# hash version 54
hash-shell
# hash v54
# Type 'exit' to quit
#>
Next Steps
After installing, see Getting Started to configure your shell.
Linux Installation
Binary Release
Linux x86_64
curl -LO https://github.com/juliojimenez/hash/releases/download/v54/hash-shell-v54-linux-x86_64
chmod +x hash-shell-v54-linux-x86_64
sudo mv hash-shell-v54-linux-x86_64 /usr/local/bin/hash-shell
hash-shell
Linux ARM64
curl -LO https://github.com/juliojimenez/hash/releases/download/v54/hash-shell-v54-linux-aarch64
chmod +x hash-shell-v54-linux-aarch64
sudo mv hash-shell-v54-linux-aarch64 /usr/local/bin/hash-shell
hash-shell
Debian/Ubuntu Packages
Ubuntu 24.04 (Noble)
curl -LO https://github.com/juliojimenez/hash/releases/download/v54/hash-shell_54-1.noble_amd64.deb
sudo dpkg -i hash-shell_54-1.noble_amd64.deb
Ubuntu 22.04 (Jammy)
curl -LO https://github.com/juliojimenez/hash/releases/download/v54/hash-shell_54-1.jammy_amd64.deb
sudo dpkg -i hash-shell_54-1.jammy_amd64.deb
Debian Bookworm
curl -LO https://github.com/juliojimenez/hash/releases/download/v54/hash-shell_54-1.bookworm_amd64.deb
sudo dpkg -i hash-shell_54-1.bookworm_amd64.deb
Debian Trixie
curl -LO https://github.com/juliojimenez/hash/releases/download/v54/hash-shell_54-1.trixie_amd64.deb
sudo dpkg -i hash-shell_54-1.trixie_amd64.deb
APT Repository (Recommended)
For automatic updates, use the APT repository:
echo "deb [trusted=yes] https://hash-shell.org/apt/ stable main" | sudo tee /etc/apt/sources.list.d/hash-shell.list
sudo apt update
sudo apt install hash-shell
See APT Installation for more details.
Verify Installation
hash-shell --version
hash-shell
macOS Installation
Homebrew (Recommended)
The easiest way to install hash on macOS:
brew install juliojimenez/hash/hash-shell
hash-shell
Upgrade
brew upgrade hash-shell
Uninstall
brew uninstall hash-shell
Binary Release
Apple Silicon (M1/M2/M3)
curl -LO https://github.com/juliojimenez/hash/releases/download/v54/hash-shell-v54-darwin-arm64
chmod +x hash-shell-v54-darwin-arm64
sudo mv hash-shell-v54-darwin-arm64 /usr/local/bin/hash-shell
hash-shell
From Source
See Building from Source for compilation instructions.
Setting as Default Shell
Homebrew Installation
sudo bash -c 'echo "$(brew --prefix)/bin/hash-shell" >> /etc/shells'
chsh -s "$(brew --prefix)/bin/hash-shell"
Binary Installation
sudo bash -c 'echo "/usr/local/bin/hash-shell" >> /etc/shells'
chsh -s /usr/local/bin/hash-shell
Log out and log back in for changes to take effect.
Verify Installation
hash-shell --version
hash-shell
FreeBSD Installation
Binary Release
FreeBSD x86_64
fetch https://github.com/juliojimenez/hash/releases/download/v54/hash-shell-v54-freebsd-x86_64
chmod +x hash-shell-v54-freebsd-x86_64
sudo mv hash-shell-v54-freebsd-x86_64 /usr/local/bin/hash-shell
hash-shell
FreeBSD ARM64
fetch https://github.com/juliojimenez/hash/releases/download/v54/hash-shell-v54-freebsd-aarch64
chmod +x hash-shell-v54-freebsd-aarch64
sudo mv hash-shell-v54-freebsd-aarch64 /usr/local/bin/hash-shell
hash-shell
From Source
See Building from Source for compilation instructions.
Setting as Default Shell
sudo sh -c 'echo "/usr/local/bin/hash-shell" >> /etc/shells'
chsh -s /usr/local/bin/hash-shell
Log out and log back in for changes to take effect.
Verify Installation
hash-shell --version
hash-shell
APT Repository Installation
Hash shell can be installed on Debian and Ubuntu systems using APT with automatic updates.
URL Change Notice: The APT repository has moved from
juliojimenez.github.io/hash/tohash-shell.org/apt/. If you previously configured the old URL, update your sources list:sudo sed -i 's|juliojimenez.github.io/hash/|hash-shell.org/apt/|' /etc/apt/sources.list.d/hash-shell.list sudo apt update
Quick Install
# Add the repository
echo "deb [trusted=yes] https://hash-shell.org/apt/ stable main" | sudo tee /etc/apt/sources.list.d/hash-shell.list
# Update and install
sudo apt update
sudo apt install hash-shell
Upgrade
Once installed via the repository, upgrade like any other package:
sudo apt update
sudo apt upgrade hash-shell
Or upgrade all packages:
sudo apt update
sudo apt upgrade
Supported Distributions
| Distribution | Codename | Architecture |
|---|---|---|
| Ubuntu 24.04 | noble | amd64 |
| Ubuntu 22.04 | jammy | amd64 |
| Debian 12 | bookworm | amd64 |
| Debian 13 | trixie | amd64 |
Direct Download (Alternative)
If you prefer not to use the repository, download packages directly:
Ubuntu 24.04 (Noble)
curl -LO https://github.com/juliojimenez/hash/releases/latest/download/hash-shell_*.noble_amd64.deb
sudo dpkg -i hash-shell_*.noble_amd64.deb
Ubuntu 22.04 (Jammy)
curl -LO https://github.com/juliojimenez/hash/releases/latest/download/hash-shell_*.jammy_amd64.deb
sudo dpkg -i hash-shell_*.jammy_amd64.deb
Debian 12 (Bookworm)
curl -LO https://github.com/juliojimenez/hash/releases/latest/download/hash-shell_*.bookworm_amd64.deb
sudo dpkg -i hash-shell_*.bookworm_amd64.deb
Note: Direct downloads won’t receive automatic updates.
Verify Installation
hash-shell
# hash v54
# Type 'exit' to quit
Set as Default Shell
echo "/usr/bin/hash-shell" | sudo tee -a /etc/shells
chsh -s /usr/bin/hash-shell
Log out and log back in for changes to take effect.
Uninstall
sudo apt remove hash-shell
sudo rm /etc/apt/sources.list.d/hash-shell.list
sudo apt update
Troubleshooting
“Repository does not have a Release file”
Make sure you’re using the correct URL:
cat /etc/apt/sources.list.d/hash-shell.list
# Should contain:
# deb [trusted=yes] https://hash-shell.org/apt/ stable main
Package Not Found After Adding Repository
sudo apt update
Dependency Issues
sudo apt --fix-broken install
GPG Key Warning
The repository uses [trusted=yes] for simplicity. This is safe for personal use but means apt won’t verify package signatures.
Docker Installation
Hash shell is available as a Docker image for containerized usage.
Quick Start
# Pull the image
docker pull juliojimenez/hash-shell
# Run interactive shell
docker run -it juliojimenez/hash-shell
Usage
Interactive Shell
docker run -it juliojimenez/hash-shell
Run a Script
Mount your scripts directory and execute:
docker run -v $(pwd):/scripts juliojimenez/hash-shell /scripts/myscript.sh
Run a Command
docker run juliojimenez/hash-shell -c 'echo "Hello from hash!"'
Building Locally
You can build the Docker image from source:
git clone https://github.com/juliojimenez/hash.git
cd hash
docker build -t hash-shell .
docker run -it hash-shell
Docker Compose
Example docker-compose.yml:
version: '3'
services:
shell:
image: juliojimenez/hash-shell
stdin_open: true
tty: true
volumes:
- ./scripts:/scripts
Run with:
docker-compose run shell
Use Cases
- Testing: Run hash in an isolated environment
- CI/CD: Execute shell scripts in containers
- Development: Test scripts across different environments
- Learning: Experiment without installing locally
Building from Source
Build hash shell from source code on any supported platform.
Prerequisites
- GCC or Clang compiler
- Make build system
- Git (for cloning)
Debian/Ubuntu
sudo apt install build-essential git
macOS
Install Xcode Command Line Tools:
xcode-select --install
FreeBSD
pkg install git gmake
Build Steps
# Clone the repository
git clone https://github.com/juliojimenez/hash.git
cd hash
# Build
make
# Install (to /usr/local/bin)
sudo make install
Build Options
Debug Build
Build with debug symbols:
make debug
Clean Build
Remove build artifacts:
make clean
make
Custom Installation Path
sudo make install PREFIX=/opt/hash
Running Tests
# Setup test framework (first time only)
make test-setup
# Run unit tests
make test
# Run integration tests
./test.sh
Verify Installation
hash-shell --version
hash-shell
Uninstall
sudo make uninstall
Development
For development setup, see the Contributing Guide.
Quick Start
Welcome to hash shell! This guide will help you get started with the basics.
Inside the shell, help lists the builtins and help NAME describes one, help trap for instance.
First Steps
After installing hash, start it by running:
hash-shell
You’ll see:
hash v54
Type 'exit' to quit
#>
Basic Commands
Hash works like any POSIX shell:
#> echo "Hello, World!"
Hello, World!
#> ls -la
# Lists files
#> cd ~/projects
# Changes directory
#> pwd
/home/user/projects
Command Line Options
| Option | Description |
|---|---|
-c string | Execute commands from string |
-i | Force interactive mode |
-l, --login | Run as a login shell |
-s | Read commands from standard input |
-v, --version | Print version information |
-h, --help | Show help message |
Examples
# Execute a command
hash-shell -c 'echo "Hello!"'
# Run a script
hash-shell script.sh
# Run as login shell
hash-shell --login
Configuration
Hash loads configuration from ~/.hashrc on startup. Create your configuration file:
cp /path/to/hash/examples/.hashrc ~/.hashrc
Or create a minimal one:
# ~/.hashrc
alias ll='ls -lah'
alias gs='git status'
set PS1='\W\g \e#>\e '
See Configuration (.hashrc) for complete details.
Key Features
- Line Editing: Arrow keys, Ctrl+A/E, history navigation
- Tab Completion: Complete commands, files, and directories
- Git Integration: Branch and status in prompt
- Aliases: Create command shortcuts
- Scripting: POSIX-compatible shell scripts
Next Steps
- Configure your .hashrc - Customize your shell
- Set up as login shell - Make hash your default
- Learn line editing - Master keyboard shortcuts
- Write scripts - Automate tasks
Configuration (.hashrc)
Hash shell supports configuration through a .hashrc file in your home directory.
Quick Start
Create your configuration file:
vim ~/.hashrc
Example .hashrc:
# Aliases
alias ll='ls -lah'
alias gs='git status'
alias gp='git push'
# Environment
export EDITOR=vim
export PATH=$HOME/bin:$PATH
# Prompt
set PS1='\W\g \e#>\e '
# Options
set colors=on
set welcome=off
Reload after editing:
source ~/.hashrc
It Is a Shell Script
.hashrc runs through the shell like any other script, so anything you can type
at the prompt works in it: functions, if and case, source for files you
share with other shells, command substitution in exports.
# Functions
mkcd() { mkdir -p "$1" && cd "$1"; }
# Conditionals
if [ -d "$HOME/bin" ]; then
export PATH="$HOME/bin:$PATH"
fi
# Shared settings
[ -f ~/.aliases ] && source ~/.aliases
Errors in the file are reported when the shell starts, so a typo shows up right
away instead of being skipped. A return ends the file and the shell carries on;
an exit ends the shell before the prompt, with that status.
Aliases
Define command shortcuts:
alias name='command'
Aliases are expanded when a command is read, as POSIX requires, so a definition
takes effect from the next line on: everything in .hashrc is ready for the
first prompt, while alias x='echo hi'; x on one line does not find x. The
name has to be the first word of a command and unquoted (\ls or 'ls' skip
an ls alias), the text may hold reserved words (alias not='! ' works in
if not test -f file; then ...), and a text that ends in a blank has the word
after it checked for an alias too (alias sudo='sudo ').
Examples
# Navigation
alias ..='cd ..'
alias ...='cd ../..'
# Safety
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Git
alias gs='git status'
alias ga='git add'
alias gc='git commit'
alias gp='git push'
alias gd='git diff'
# Docker
alias d='docker'
alias dc='docker-compose'
alias dps='docker ps'
Managing Aliases
# List all aliases
alias
# Show specific alias
alias ll
# Remove alias
unalias ll
Environment Variables
Set variables with export:
export VARIABLE=value
export VARIABLE='value with spaces'
export VARIABLE="value with $substitution"
Common Variables
# Editor
export EDITOR=vim
export VISUAL=vim
# Path
export PATH=$HOME/bin:$PATH
# Locale
export LANG=en_US.UTF-8
# Custom
export MY_PROJECT=~/projects/myapp
Shell Options
Configure behavior with set:
set option=value
Available Options
| Option | Values | Description |
|---|---|---|
colors | on/off | Enable colored output |
welcome | on/off | Show welcome message |
prompt | classic, plain, minimal, two-line, powerline, list | Pick a prompt preset; list shows them |
PS1 | format | Custom prompt |
color.<element> | style | Color of one element, e.g. color.prompt=bold,blue |
syntax_highlight | on/off | Highlight the command line as you type |
autosuggest | on/off | Suggest completions from history |
danger_highlight | on/off | Highlight dangerous commands |
set colors=on
set welcome=off
set PS1='\W\g \e#>\e '
Prompt Customization
Set your prompt with the PS1 variable:
# Current directory + git + exit color
set PS1='\W\g \e#>\e '
# Full path + git
set PS1='\w\g \e#>\e '
# User@host:path
set PS1='\u@\h:\w\$ '
Escape Sequences
| Sequence | Description |
|---|---|
\w | Full current path |
\W | Current directory name |
\u | Username |
\h | Hostname, up to the first dot (\H the full name) |
\g | Git branch with status (\b the branch alone) |
\e | Exit code color, between \e...\e (\? the status itself when not 0) |
\$ | $ for user, # for root |
\t \T \@ \d | Time (24-hour, 12-hour, with am/pm) and date |
\j \! | Background jobs, history number |
\s \v | Shell name and version |
\n | Newline |
\\ | A backslash |
The full list, with examples, is on the Prompt Customization page; set prompt=NAME picks a preset instead.
See Prompt Customization for complete details.
Comments
Lines starting with # are ignored:
# This is a comment
alias ll='ls -lah' # Inline comment
Tips
Organize by Category
# ============================================================================
# NAVIGATION
# ============================================================================
alias ..='cd ..'
alias projects='cd ~/projects'
# ============================================================================
# GIT
# ============================================================================
alias gs='git status'
alias gp='git push'
Test Before Adding
Try aliases interactively first:
#> alias test='echo "works"'
#> test
works
# Now add to .hashrc
Reload After Changes
source ~/.hashrc
Troubleshooting
Alias Not Working
Check syntax (quotes required):
# Wrong
alias ll=ls -lah
# Correct
alias ll='ls -lah'
Variable Not Visible to Programs
MY_VAR=value sets a shell variable. Programs you run only see it after export:
MY_VAR=value # shell variable only
export MY_VAR=value # also in the environment
Config Not Loading
Check file location and reload:
ls -la ~/.hashrc
source ~/.hashrc
Login Shell Setup
Hash supports proper login shell behavior, loading different startup files depending on how it’s invoked.
Setting Hash as Default Shell
Linux (chsh)
sudo bash -c 'echo "/usr/local/bin/hash-shell" >> /etc/shells'
chsh -s /usr/local/bin/hash-shell
Linux (usermod)
sudo usermod -s /usr/local/bin/hash-shell your_username
macOS
sudo bash -c 'echo "/usr/local/bin/hash-shell" >> /etc/shells'
chsh -s /usr/local/bin/hash-shell
If installed with Homebrew:
sudo bash -c 'echo "$(brew --prefix)/bin/hash-shell" >> /etc/shells'
chsh -s "$(brew --prefix)/bin/hash-shell"
FreeBSD
sudo sh -c 'echo "/usr/local/bin/hash-shell" >> /etc/shells'
chsh -s /usr/local/bin/hash-shell
Note: Log out and log back in for changes to take effect.
Login Shell Detection
Hash considers itself a login shell when:
argv[0]starts with-(how SSH/login invoke shells)--loginor-lflag is used
Login shells display “(login)” in the welcome message.
Startup File Order
Login Shell
When invoked as a login shell:
/etc/profile- System-wide settings- User profile (first found):
~/.hash_profile~/.hash_login~/.profile
~/.hashrc- Interactive settings
Non-Login Interactive Shell
~/.hashrc only
Configuration Files
~/.hash_profile
User-specific login configuration:
# Environment
export EDITOR=vim
export PAGER=less
# PATH
export PATH=$HOME/bin:$HOME/.local/bin:$PATH
~/.hashrc
Interactive settings:
# Aliases
alias ll='ls -lah'
alias gs='git status'
# Prompt
set PS1='\W\g \e#>\e '
~/.hash_logout
Executed when exiting a login shell:
# Clear screen
clear
# Farewell message
echo "Goodbye! Session ended at $(date)"
# Cleanup
rm -rf ~/tmp/session_* 2>/dev/null
The logout Command
Use logout to exit login shells:
# In a login shell
#> logout
Bye :)
# In a non-login shell
#> logout
hash: logout: not a login shell
# Use 'exit' instead
Best Practices
Separate Concerns
- ~/.hash_profile: Environment variables, PATH
- ~/.hashrc: Aliases, prompt settings
- ~/.hash_logout: Cleanup tasks
Example Setup
~/.hash_profile:
export EDITOR=vim
export GOPATH=$HOME/go
export PATH=$HOME/bin:$GOPATH/bin:$PATH
~/.hashrc:
set PS1='\u@\h:\W\g #> '
alias ll='ls -lah'
set colors=on
~/.hash_logout:
clear
echo "Session ended. Goodbye!"
Testing
# Test as login shell
hash-shell --login
# Check for "(login)" in welcome message
hash v54 (login)
Type 'exit' to quit
Interactive Features
Hash shell includes powerful interactive features for efficient command-line use.
Features Overview
| Feature | Description |
|---|---|
| Line Editing | Cursor navigation, editing shortcuts |
| Tab Completion | Complete commands, files, directories |
| Command History | Navigate and search previous commands |
| Prompt Customization | Git integration, colors, custom format |
Quick Reference
Line Editing
| Key | Action |
|---|---|
Ctrl+A | Move to beginning of line |
Ctrl+E | Move to end of line |
Ctrl+U | Delete to beginning |
Ctrl+K | Delete to end |
Ctrl+W | Delete word backward |
Ctrl+L | Clear screen |
Ctrl+C | Cancel current line |
History Navigation
| Key | Action |
|---|---|
Up | Previous command |
Down | Next command |
!! | Repeat last command |
!n | Run command number n |
!prefix | Run last command starting with prefix |
Tab Completion
| Context | Completes |
|---|---|
| First word | Commands, aliases, builtins |
| Other words | Files, directories |
| Double TAB | Show all matches |
Unknown Commands
When a command is not found, an interactive shell says so and, when a builtin,
alias, function or executable on PATH is within one or two edits of what was
typed, suggests it:
#> ehco hi
hash: ehco: command not found
Did you mean: echo?
#> sl
hash: sl: command not found
Did you mean one of these? ls nl pl
Only the closest names are offered, the status stays 127, and scripts and
hash -c get the plain message.
Default Prompt
The default prompt shows:
/home/user/projects git:(main) #>
- Blue path
- Green/Yellow git status (clean/dirty)
- Cyan branch name
- Blue/Red
#>based on exit code
Configuration
Configure interactive features in ~/.hashrc:
# Custom prompt
set PS1='\W\g \e#>\e '
# Enable colors
set colors=on
Line Editing
Hash shell includes a custom line editor with full cursor navigation and editing capabilities.
Key Bindings
Cursor Movement
| Key | Action |
|---|---|
Left Arrow | Move cursor left |
Right Arrow | Move cursor right |
Up Arrow | Previous command in history |
Down Arrow | Next command in history |
Ctrl+A | Move to beginning of line |
Ctrl+E | Move to end of line |
Home | Move to beginning of line |
End | Move to end of line |
Editing
| Key | Action |
|---|---|
Backspace | Delete character before cursor |
Delete | Delete character at cursor |
Ctrl+H | Same as Backspace |
Ctrl+U | Delete from cursor to beginning |
Ctrl+K | Delete from cursor to end |
Ctrl+W | Delete word backward |
Other
| Key | Action |
|---|---|
Tab | Auto-complete |
Ctrl+L | Clear screen |
Ctrl+C | Cancel current line |
Ctrl+D | EOF (exit if line empty) |
Enter or Ctrl+J | Submit command |
Features
Insert Mode
Hash uses insert mode (like bash):
- Typing inserts characters at cursor position
- Existing text shifts right
- Edit anywhere in the line
hello world
^
cursor
Type 'beautiful ' → hello beautiful world
Typing Ahead
Text typed while a command is still running is not lost. The terminal echoes it once as you type it, and when the prompt comes back the editor reads it and runs it, so you can queue the next command without waiting:
#> sleep 2
echo next # typed during the sleep
#> echo next # the editor shows it again, then runs it
next
Keys typed between pressing Enter and the command’s first read go to the
command, as they do in other shells.
Tab Completion
Press TAB to auto-complete:
Single match:
#> ec<TAB>
#> echo # Completed with space
Multiple matches - first TAB:
#> cat te<TAB>
#> cat test # Common prefix
Multiple matches - second TAB:
test.txt test.md testing.log
#> cat test
See Tab Completion for details.
Ctrl+C Handling
Cancel current input and get a fresh prompt:
#> some long command^C
#>
Ctrl+D Behavior
- On empty line: Exits the shell
- On non-empty line: Does nothing
Vi Mode
set -o vi switches the editor to vi’s modal editing; set -o emacs (the
default) switches back. Both appear in set -o, and set +o prints the one in
effect as a command you can put in ~/.hashrc.
Each line starts in insert mode, where every key works as in emacs mode. Esc
enters command mode: the cursor stands on a character, motions move it,
operators act on a motion, and i, a, I, A return to inserting. Words are
blank-separated. Counts are not implemented.
| Key | Action |
|---|---|
Esc | Command mode |
h l (or arrows) | Left, right |
0 ^ $ | Start, start, end of line |
w b e | Next word, previous word, end of word |
i a I A | Insert here, after the cursor, at the start, at the end |
x X | Delete the character under, before the cursor |
d + motion, dd, D | Delete through a motion, the whole line, to the end |
c + motion, cc, C, s, S | Delete the same, then insert (cw changes to the end of the word) |
y + motion, yy | Copy to the cut buffer |
p P | Put the cut buffer after, before the cursor |
r + char | Replace the character under the cursor |
~ | Toggle case and move right |
u | Undo the last edit (again redoes) |
k j (or arrows) | Older, newer history entry, cursor at the start |
/ | Incremental history search: type, Enter runs the match, Esc keeps it for editing |
Enter | Run the line, from either mode |
#> set -o vi
#> echo helo # Esc, h, i, l, Esc, Enter
hello
Tips & Tricks
Quick Edits
# Typed wrong command
#> cat file.tx
# Press Ctrl+A, Ctrl+K, type correct command
Delete Mistakes
#> echo hello worldddd
# Press Ctrl+W to delete "worldddd"
#> echo hello
Clear and Restart
#> some complex command
# Press Ctrl+U to clear
#>
Cancel Without Running
#> rm -rf /important
# Press Ctrl+C
^C
#>
Troubleshooting
Keys Not Working
Check terminal type:
echo $TERM
# Should be xterm, xterm-256color, etc.
Arrow Keys Print Escape Sequences
Set proper terminal:
export TERM=xterm-256color
Comparison with Bash
Supported (Same as Bash)
- Arrow key navigation
- History navigation
- Ctrl+A, Ctrl+E
- Ctrl+U, Ctrl+K, Ctrl+W
- Ctrl+L, Ctrl+C, Ctrl+D
- Home/End keys
- Insert mode
- Ctrl+R reverse search
- Vi mode (
set -o vi), the subset listed above
Not Yet Supported
- Ctrl+T (transpose)
- Alt key bindings
- Vi counts and text objects
- Custom key bindings
Tab Completion
Hash completes commands, files and directories, and knows what many commands expect as arguments: variable names after $, directories after cd, aliases after unalias, git subcommands and branches, make targets, manual pages. The complete builtin adds completions for any command.
Basic Usage
Command Completion
Press TAB after typing part of a command:
#> ec<TAB>
#> echo # Completed!
#> gi<TAB>
#> git # Completed from PATH
File/Directory Completion
#> cat test<TAB>
#> cat testfile.txt # Completed!
#> cd Doc<TAB>
#> cd Documents/ # Directory with trailing /
Multiple Matches
First TAB - Complete common prefix:
#> cat test<TAB>
#> cat test # Common prefix
Second TAB - Show all matches:
#> cat test<TAB><TAB>
testfile.txt test.md test_data.csv
#> cat test
What Gets Completed
First Word (Command)
Completes from:
- Built-in commands (cd, exit, alias, etc.)
- Aliases from .hashrc
- Shell functions
- Executables in PATH, scanned once and rescanned when
PATHchanges or after 15 seconds
#> g<TAB><TAB>
ga gc gd git gl gp gs
Subsequent Words
By default, files and directories: relative and absolute paths, with tilde
expansion. A name typed without a directory completes to a bare name (afile,
not ./afile). Several commands get something better suited:
| Command | Completes |
|---|---|
cd, pushd, rmdir | Directories only |
unalias | Alias names |
unset | Variable names; function names after -f |
export, readonly, local | Variable names |
command, exec, builtin, type, which, sudo, doas, nohup, nice, time, env, xargs, watch | A command for the first operand, then files |
git | Subcommands; branches, tags and remotes for checkout, switch, merge, rebase, log, diff, push, pull and friends; files for add, rm, restore |
make, gmake | Targets of GNUmakefile, makefile or Makefile in the current directory (-f and -C complete files and directories) |
man | Page names from MANPATH or manpath |
Options (words starting with -) are not completed.
Variables
After $ or ${, shell variables and the environment:
#> echo $HO<TAB>
#> echo $HOME
#> echo ${HO<TAB>
#> echo ${HOME}
Users
~ followed by the start of a login name completes to ~name/:
#> ls ~ro<TAB>
#> ls ~root/
#> cat /<TAB>
bin/ boot/ dev/ etc/ home/ ...
#> cd ~/.c<TAB>
#> cd ~/.config/
Programmable Completion
complete records how a command’s arguments are completed, in the spirit of
bash’s builtin but without arrays:
complete -W "start stop restart status" myservice
complete -F _mytool_complete mytool
complete -d cdto # directories only
complete -c sudo # commands (sudo already has this built in)
complete -o default -W "init build" tool # files when no word matches
| Option | Meaning |
|---|---|
-W wordlist | The words in wordlist (separated by blanks) that start with the current word |
-F function | Run function; every line it prints that starts with the current word is a candidate |
-a -b -c -d -f -u -v | Aliases, builtins, commands, directories, files, users, variables |
-o default | Files when nothing else matched |
-o dirnames | Directories when nothing else matched |
-p [name...] | Print the specifications, as lines that can be typed back |
-r [name...] | Remove them (all of them without names) |
A -F function runs with $1 set to the command, $2 to the word being
completed and $3 to the word before it, and with COMP_LINE, COMP_POINT
and COMP_CWORD set to the whole line, the cursor position and the index of
the word. It prints candidates, one per line; hash keeps those that start with
$2, so the function may print its whole vocabulary or filter it itself:
_mytool_complete() {
case $3 in
--format) echo json; echo yaml; echo table ;;
*) mytool --list-commands ;;
esac
}
complete -F _mytool_complete mytool
Put complete lines in ~/.hashrc to have them every session.
Features
Directory Handling
Directories get trailing /:
#> cd Doc<TAB>
#> cd Documents/
Tilde Expansion
#> cat ~/.<TAB>
~/.bashrc ~/.config/ ~/.hashrc ...
Path Completion
#> ls ~/projects/hash/src/m<TAB>
#> ls ~/projects/hash/src/main.c
Case Sensitivity
Completion is case-sensitive:
#> cat Test<TAB> # Won't match "test.txt"
#> cat test<TAB> # Matches "test.txt"
Behavior
Single Match
- Completes full name
- Adds space after (ready for next arg)
- Directories get
/
Multiple Matches
First TAB: Complete common prefix Second TAB: Show all matches in columns
No Matches
Bell/beep sound, line unchanged.
After Operators
Completion works after command chaining:
#> ls && ca<TAB>
#> ls && cat
#> cd /tmp ; pw<TAB>
#> cd /tmp ; pwd
Tips & Tricks
Quick Directory Navigation
#> cd /u/l/b<TAB>
#> cd /usr/local/bin/
Exploring Directories
#> ls /etc/<TAB><TAB>
# Shows all files in /etc/
Command Discovery
#> git<TAB><TAB>
git git-shell gitk ...
Limitations
- Options (
--long,-x) are not completed;complete -Wcan supply them for a command. gitsubcommand detection does not know which options take an argument (git -C dir <TAB>seesdiras the subcommand).- Candidates are plain words: no quoting of names with spaces.
Comparison with Bash
| Feature | Hash | Bash |
|---|---|---|
| Command completion | Yes | Yes |
| File/directory completion | Yes | Yes |
| Alias completion | Yes | Yes |
| Path completion | Yes | Yes |
| Double-TAB shows matches | Yes | Yes |
| Variable completion | Yes | Yes |
User completion (~name) | Yes | Yes |
Directories after cd | Yes | With bash-completion |
| git, make, man | Yes | With bash-completion |
| Programmable completion | complete -W, -F, actions | Yes (with compgen, arrays) |
Command History
Hash shell maintains persistent command history with bash compatibility.
Basic Usage
Up/Down Arrows
Navigate through history:
#> echo first
#> echo second
#> echo third
# Press Up arrow
#> echo third # Most recent
# Press Up again
#> echo second
History Command
List all commands:
#> history
0 ls -la
1 cd /tmp
2 echo hello
3 git status
Multi-line Commands
A command typed over several lines is one history entry. A for loop, an
if, a function or a here-document entered under the continuation prompt is
recorded whole once it is complete, so Up brings the entire command back,
spread over its lines, and Enter runs it again:
#> for i in 1 2; do
> echo "$i"
> done
1
2
# Press Up: the three lines come back together
#> for i in 1 2; do
echo "$i"
done
history lists such an entry on several lines, !n re-runs all of it, and
Ctrl-C on an unfinished command records nothing.
History Expansion
!! - Last Command
#> echo hello
hello
#> !!
echo hello
hello
#> apt update
Permission denied
#> sudo !!
sudo apt update
!n - Command by Number
#> history
0 ls -la
1 cd /tmp
2 echo test
#> !1
cd /tmp
!-n - Relative History
#> echo first
#> echo second
#> echo third
#> !-2
echo second
second
!prefix - Last Command Starting With
#> git status
#> ls -la
#> pwd
#> !git
git status
Environment Variables
HISTSIZE
Commands kept in memory:
export HISTSIZE=1000 # Default
export HISTSIZE=5000 # More
export HISTSIZE=-1 # Unlimited
HISTFILESIZE
Commands saved to file:
export HISTFILESIZE=2000 # Default
export HISTFILESIZE=-1 # Unlimited
HISTFILE
History file location:
# Default
~/.hash_history
# Custom
export HISTFILE=~/my_history
History File Format
The file holds one #<seconds> line before each entry, the same extended
format bash uses with HISTTIMEFORMAT, so an entry may span several lines and
the time it was entered is kept:
#1762459200
for i in 1 2; do
echo "$i"
done
#1762459207
echo done
A history file from an earlier release, with one command per line, still loads; it is rewritten in this format the next time a command is added.
HISTCONTROL
Control what gets saved:
export HISTCONTROL=ignorespace # Skip space-prefixed
export HISTCONTROL=ignoredups # Skip consecutive dups
export HISTCONTROL=ignoreboth # Both (recommended)
export HISTCONTROL=erasedups # Remove all dups
Privacy Feature
Commands starting with space are NOT saved:
#> echo public
# Saved to history
#> echo private
# NOT saved (leading space)
What Gets Saved
Only the lines hash reads as its own input:
- Commands typed at the prompt, whether they succeed or fail
- Multi-line commands (&&, ||, ;)
- Lines of a script run with
hash-shell -i script
What Doesn’t Get Saved
- Empty lines
- Whitespace-only lines
- Duplicate of previous command
- Commands starting with space
- Lines of files loaded with
sourceor., including~/.hashrcand the startup files - Commands run through
eval, or inside loop and function bodies - Anything after
set -o nolog
History File
Location
Default: ~/.hash_history
Incremental Saving
History saves immediately after each command:
#> echo test1
# Immediately saved
#> echo test2
# Also saved
# Even if shell crashes, both are preserved!
Manual Commands
history -w # Force save
history -r # Reload from file
history -c # Clear history (memory only)
Examples
Repeat Last Command
#> make
#> !!
make
Repeat with Sudo
#> apt update
Permission denied
#> sudo !!
sudo apt update
History Search
#> history | grep git
# See all git commands
Private Commands
#> export API_KEY=secret
# Leading space - not saved!
Troubleshooting
History Not Saving
Check file permissions:
ls -la ~/.hash_history
!! Not Working
Make sure you’ve run a command first.
Up Arrow Not Working
Check terminal:
echo $TERM
Comparison with Bash
| Feature | Hash | Bash |
|---|---|---|
!! | Yes | Yes |
!n | Yes | Yes |
!-n | Yes | Yes |
!prefix | Yes | Yes |
| Up/Down arrows | Yes | Yes |
| History file | Yes | Yes |
| Privacy (space prefix) | Yes | Yes |
Ctrl+R | No | Yes |
!?pattern | No | Yes |
^old^new | No | Yes |
Prompt Customization
Hash shell supports powerful prompt customization through the PS1 variable.
Presets
Pick a prompt by name and it applies at once:
set prompt=two-line
set prompt=list shows every preset with a live sample, the current one
marked with *:
| Preset | Look |
|---|---|
classic | |
plain | |
minimal | |
two-line | |
powerline |
classicis the default: path, git branch and status, and#>in the colour of the last exit status.plainis the look of a classic bash prompt,user@host:path$, without git.minimalshows the directory name and a chevron coloured by the last status.two-lineputs user, host, path and git on one line and the chevron on the next, with a failed status in red before the line break.powerlinedraws coloured segments with triangle separators. It uses characters every monospace font has, so no patched font is needed.
Put the line in ~/.hashrc to keep it. The presets use the colour elements
below (path, git_*, prompt, prompt_error), so set color.path=...
changes them too, except the powerline segments, whose backgrounds are part of
the look. A name that is not a preset fails with the list of names and status 1.
Default Prompt
/home/user/projects git:(main) #>
- Blue current path
- Green
git:(yellow if dirty) - Cyan branch name
- Blue
#>(red if last command failed)
Quick Start
In ~/.hashrc:
# Simple prompt
set PS1='\W #> '
# Full path with git
set PS1='\w\g \e#>\e '
# User@host:path
set PS1='\u@\h:\w\$ '
Or as environment variable:
export PS1='\w\g \e#>\e '
Continuation Prompt (PS2)
When a line does not finish a command, for example for f in *.txt on its own, hash shows the continuation prompt and keeps reading until the compound command is complete:
#> for f in *.txt
> do
> echo "$f"
> done
The default is > . Set PS2 to change it:
export PS2='... '
Press Ctrl+C at the continuation prompt to abandon the unfinished command.
Escape Sequences
Path Information
| Sequence | Description | Example |
|---|---|---|
\w | Full current path | /home/user/projects |
\W | Current directory only | projects |
User Information
| Sequence | Description |
|---|---|
\u | Username |
\h | Hostname |
\$ | $ for user, # for root |
Git Integration
| Sequence | Description |
|---|---|
\g | Git branch with status |
The \g sequence:
- Shows nothing outside git repos
- Shows
git:(branch)in repos git:is green if clean, yellow if dirty- Branch name is cyan
Exit Code Indicator
| Sequence | Description |
|---|---|
\e | Sets color based on exit code |
Use \e before and after text:
set PS1='\w \e#>\e '
# ^ ^
# | Reset color
# Set color (blue=success, red=fail)
Special Characters
| Sequence | Output |
|---|---|
\$ | # for root, $ otherwise |
\n | Newline |
\\ | A backslash |
\[ \] | Ignored; bash wraps colour codes in them and hash measures the codes itself |
Status, Time, Jobs
| Sequence | Output |
|---|---|
\? | The last exit status when it was not 0, otherwise nothing |
\b | The git branch alone, nothing outside a repository |
\t \T \@ | The time: 24-hour, 12-hour, 12-hour with am/pm |
\d | The date, Thu Nov 06 |
\j | The number of background jobs |
\! | The history number of the command about to be entered |
\s \v | The shell name and version |
\H | The full host name (\h stops at the first dot) |
Example Prompts
Minimal
set PS1='\W #> '
# Output: projects #>
Classic
set PS1='\u@\h:\w \$ '
# Output: user@hostname:/home/user $
Full Path with Git
set PS1='\w\g \e#>\e '
# Output: /home/user/projects git:(main) #>
Two-Line
set PS1='\w\g\n\e#>\e '
# Output:
# /home/user/projects git:(main)
# #>
Powerline Style
set prompt=powerline # the preset; see Presets above
Color Behavior
Path Colors
\w and \W are bold blue
Git Colors
git:is green when cleangit:is yellow when dirty- Branch name is cyan
Exit Code Colors
\esets blue on success (exit 0)\esets red on failure (exit non-zero)
Tips
Test Before Setting
#> export PS1='\W\g \e#>\e '
projects git:(main) #>
Keep It Simple
Complex prompts can slow down the shell:
# Fast
set PS1='\W #> '
# Slower (git checks)
set PS1='\w\g \e#>\e '
Two-Line for Long Paths
set PS1='\w\g\n\e#>\e '
Disable Git in Large Repos
set PS1='\w \e#>\e ' # No \g
Troubleshooting
Colors Not Showing
Enable colors:
set colors=on
Check terminal:
echo $TERM
# Should be xterm-256color or similar
Git Branch Not Showing
Verify you’re in a git repo:
git status
Ensure \g is in your PS1.
Exit Colors Not Working
Wrap characters between two \e:
# Wrong
set PS1='\w \e#> '
# Correct
set PS1='\w \e#>\e '
Comparison with Bash
Similar
\w,\W,\u,\h,\H,\$,\t,\T,\@,\d,\j,\!,\s,\v,\[,\]work the same- Color support
- Environment variable support
Hash-Specific
set prompt=NAME- Presets\?- Last exit status when non-zero,\b- bare git branch\g- Git integration\e- Exit code color- Automatic
~substitution
Not Supported (Yet)
\D{format}- Date with a custom formatPROMPT_COMMAND- Use$(...)in PS1 instead
Shell Scripting
Hash shell supports POSIX-compatible shell scripting for automation and reusable scripts.
Running Scripts
Shebang Line
Create a script with the hash shebang:
#!/usr/local/bin/hash-shell
echo "Hello from hash!"
Make executable and run:
chmod +x script.sh
./script.sh
Direct Execution
hash-shell script.sh
Command String
hash-shell -c 'echo "Hello"; echo "World"'
From Standard Input
echo 'echo "Hello"' | hash-shell -s
Script Arguments
Positional Parameters
#!/usr/local/bin/hash-shell
echo "Script name: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Arg count: $#"
Run:
./script.sh hello world
# Output:
# Script name: ./script.sh
# First arg: hello
# Second arg: world
# All args: hello world
# Arg count: 2
Parsing Options
getopts reads the options a script was given one at a time; shift then
drops them so $1 is the first operand:
#!/usr/local/bin/hash-shell
verbose=0
while getopts "vo:" opt; do
case $opt in
v) verbose=1 ;;
o) output=$OPTARG ;;
?) echo "usage: $0 [-v] [-o file] args" >&2; exit 2 ;;
esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose output=$output args=$*"
$ ./script.sh -v -o out.txt a b
verbose=1 output=out.txt args=a b
A letter followed by : in the option string takes an argument, attached
(-oout.txt) or as the next word. Options can be clustered (-vo out.txt),
and -- ends them. An unknown option or a missing argument sets opt to ?
and prints a message; start the option string with : to get ? or : in
opt and the offending letter in OPTARG instead, with no message.
Special Variables
| Variable | Description |
|---|---|
$0 | Script name |
$1-$9 | Positional arguments |
$# | Number of arguments |
$@ | All arguments (separate words) |
$* | All arguments (single word) |
$? | Exit code of last command |
$$ | Process ID of shell |
Functions
greet() {
echo "Hello, $1!"
}
greet "World"
With return value:
is_even() {
if [ $(($1 % 2)) -eq 0 ]; then
return 0 # true
else
return 1 # false
fi
}
if is_even 4; then
echo "4 is even"
fi
Local Variables
local keeps a function’s variables out of the caller’s way. The previous
value comes back when the function returns, an exported variable stays exported
while it is shadowed, and a name given without a value is unset inside the
function:
count=0
bump() {
local count=10
count=$((count + 1))
echo "inside: $count"
}
bump
echo "outside: $count"
inside: 11
outside: 0
Scoping is dynamic, as in dash and bash: a function called from bump sees
its count. local outside a function is an error.
A function may call itself, through eval and . too, 1000 levels deep by
default. One level more fails with hash: f: maximum function nesting level exceeded (1000): the whole command is abandoned with status 1, an interactive
shell shows the next prompt, and a script stops there. FUNCNEST changes the
limit (FUNCNEST=50); FUNCNEST=0 removes the depth limit and leaves only the
guard that refuses a call when the C stack is about to run out. Either way,
runaway recursion ends with a message rather than a segmentation fault.
Variables
Assignment
NAME="value" # No spaces around =
export NAME="value" # Export to environment
Expansion
echo $NAME # Simple
echo ${NAME} # Braced
echo "${NAME}" # Quoted (preserves whitespace)
Exit Codes
#!/usr/local/bin/hash-shell
if [ ! -f "$1" ]; then
echo "Error: File not found" >&2
exit 1
fi
# Process file...
exit 0
Common codes:
0- Success1- General error2- Misuse of command
Comments
# This is a comment
echo "Hello" # Inline comment
Best Practices
- Always quote variables:
"$var"prevents word splitting - Use meaningful names:
FILE_COUNTnotfc - Check for errors: Test return codes
- Add comments: Explain complex logic
- Use exit codes: Return 0 for success
- Validate input: Check arguments first
Practical Example
#!/usr/local/bin/hash-shell
# Backup script
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d)
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p "$BACKUP_DIR"
fi
for dir in /home/*; do
if [ -d "$dir" ]; then
user=$(basename "$dir")
tar -czf "$BACKUP_DIR/${user}_${DATE}.tar.gz" "$dir"
echo "Backed up: $user"
fi
done
echo "Backup complete!"
See Also
Variables & Expansion
Hash shell supports environment variable expansion in commands and arguments.
Basic Syntax
$VAR - Simple Expansion
#> export NAME=Julio
#> echo Hello $NAME
Hello Julio
${VAR} - Braced Expansion
Use braces when concatenating:
#> export PRE=test
#> echo ${PRE}ing
testing
#> echo $PREing
# Tries to expand $PREing (undefined)
Special Variables
Every special parameter below expands the same way with or without braces and
inside double quotes: "$$", ${$}, ${?}, ${!}, ${#}, ${-}, ${@}
and ${*} all work, and the braced forms take the usual modifiers
(${?:-0}, ${#?}). $$ is the pid of the shell itself, also inside
pipelines, subshells, $( ) and background jobs.
$? - Exit Code
#> true
#> echo $?
0
#> false
#> echo $?
1
$$ - Process ID
#> echo $$
12345
$LINENO - Current Line
The line of the current command: within the script, the -c string or the
eval text being run, and from the definition line inside a function body.
Syntax errors report the same line.
#> echo $LINENO
1
$0 - Shell Name
#> echo $0
hash
Variable Name Rules
Valid names:
- Start with letter or underscore
- Contain letters, numbers, underscores
- Case-sensitive
$HOME # Valid
$MY_VAR # Valid
$_private # Valid
$123 # Invalid (starts with number)
$my-var # Invalid (hyphen)
Escaping
Prevent expansion with backslash:
#> echo \$HOME
$HOME
#> echo Price: \$5
Price: $5
Quote Handling
Double Quotes - Variables Expand
#> export NAME=Julio
#> echo "Hello $NAME"
Hello Julio
Single Quotes - No Expansion
#> echo 'Hello $NAME'
Hello $NAME
Common Patterns
Building Paths
#> export PROJECT=myapp
#> export BUILD_DIR=/tmp/builds
#> mkdir -p ${BUILD_DIR}/${PROJECT}
PATH Manipulation
#> export PATH=$HOME/bin:$PATH
Configuration
# In .hashrc
export EDITOR=vim
export PROJECT_DIR=~/projects
alias edit='$EDITOR'
alias proj='cd $PROJECT_DIR'
Undefined Variables
Expand to empty string:
#> unset UNDEFINED
#> echo "Value: $UNDEFINED"
Value:
Parameter Expansion Forms
The POSIX forms are all available:
| Form | Result |
|---|---|
${VAR:-word} | $VAR, or word when unset or empty (${VAR-word}: only when unset) |
${VAR:=word} | Assign word when unset or empty, then expand |
${VAR:+word} | word when set and non-empty, otherwise nothing |
${VAR:?word} | $VAR, or print word and fail when unset or empty |
${#VAR} | Length of the value |
${VAR#pattern}, ${VAR##pattern} | Remove the shortest, longest matching prefix |
${VAR%pattern}, ${VAR%%pattern} | Remove the shortest, longest matching suffix |
The pattern word of ${VAR#pattern}, ${VAR##pattern}, ${VAR%pattern} and
${VAR%%pattern} is expanded before it is used: ${file#*"$prefix"} removes a
literal prefix held in a variable, ${t##$glob} uses the variable’s value as a
pattern, and anything quoted in the word matches itself. # and % remove the
shortest match, ## and %% the longest, and the shortest match may be empty
(${t#*} is $t).
Control Structures
Hash shell supports POSIX-compatible control structures for flow control.
They work at the interactive prompt as well as in scripts, either on one line (for i in 1 2; do echo $i; done) or typed one line at a time, in which case hash shows the continuation prompt > until the command is complete. Brace groups ({ echo a; echo b; }) must stay on one line for now.
If/Then/Else
Syntax
if command; then
commands
fi
if command; then
commands
else
commands
fi
if command; then
commands
elif command; then
commands
else
commands
fi
Examples
# Simple if
if [ -f "/etc/passwd" ]; then
echo "passwd file exists"
fi
# If/else
if [ "$USER" = "root" ]; then
echo "Running as root"
else
echo "Running as $USER"
fi
# If/elif/else
if [ $count -lt 0 ]; then
echo "Negative"
elif [ $count -eq 0 ]; then
echo "Zero"
else
echo "Positive"
fi
Any Command as Condition
if grep -q "pattern" file.txt; then
echo "Found"
fi
if command -v git > /dev/null; then
echo "Git installed"
fi
For Loops
Syntax
for var in list; do
commands
done
Examples
# List of words
for name in Alice Bob Charlie; do
echo "Hello, $name"
done
# Files
for file in *.txt; do
echo "Processing: $file"
done
# Arguments
for arg in "$@"; do
echo "Argument: $arg"
done
# Numbers
for i in $(seq 1 5); do
echo "Number: $i"
done
While Loops
Syntax
while command; do
commands
done
Examples
count=0
while [ $count -lt 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
# Read lines
while read line; do
echo "Line: $line"
done < file.txt
# Infinite loop
while true; do
echo "Press Ctrl+C"
sleep 1
done
Until Loops
Syntax
until command; do
commands
done
Example
count=0
until [ $count -ge 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
Case Statements
Syntax
case word in
pattern1)
commands
;;
pattern2|pattern3)
commands
;;
*)
default
;;
esac
Examples
case "$1" in
start)
echo "Starting..."
;;
stop)
echo "Stopping..."
;;
*)
echo "Usage: $0 {start|stop}"
;;
esac
# Pattern matching
case "$filename" in
*.txt)
echo "Text file"
;;
*.sh)
echo "Shell script"
;;
*)
echo "Unknown"
;;
esac
Nesting
for dir in /home/*; do
if [ -d "$dir" ]; then
for file in "$dir"/*.txt; do
if [ -f "$file" ]; then
echo "Found: $file"
fi
done
fi
done
Common Mistakes
Missing Spaces
# Wrong
if [-f "$file"]; then
# Correct
if [ -f "$file" ]; then
Unquoted Variables
# Wrong
for file in $files; do
# Correct
for file in "$files"; do
= vs -eq
# String comparison
if [ "$str" = "value" ]; then
# Numeric comparison
if [ $num -eq 5 ]; then
Test Command
The test command (or [ ]) evaluates expressions for use in conditionals.
File Tests
| Test | Description |
|---|---|
-e file | File exists |
-f file | Is a regular file |
-d file | Is a directory |
-r file | Is readable |
-w file | Is writable |
-x file | Is executable |
-s file | Has size > 0 |
-L file | Is a symbolic link |
Examples
if [ -f "/etc/passwd" ]; then
echo "File exists"
fi
if [ -d "$dir" ]; then
echo "Is a directory"
fi
if [ -r "$file" ] && [ -w "$file" ]; then
echo "Readable and writable"
fi
String Tests
| Test | Description |
|---|---|
-z string | String is empty |
-n string | String is not empty |
s1 = s2 | Strings are equal |
s1 != s2 | Strings are not equal |
Examples
if [ -z "$var" ]; then
echo "Variable is empty"
fi
if [ "$USER" = "root" ]; then
echo "Running as root"
fi
if [ "$a" != "$b" ]; then
echo "Strings differ"
fi
Numeric Tests
| Test | Description |
|---|---|
n1 -eq n2 | Equal |
n1 -ne n2 | Not equal |
n1 -lt n2 | Less than |
n1 -le n2 | Less than or equal |
n1 -gt n2 | Greater than |
n1 -ge n2 | Greater than or equal |
Examples
if [ $count -eq 0 ]; then
echo "Count is zero"
fi
if [ $x -lt 10 ]; then
echo "x is less than 10"
fi
if [ $a -ge $b ]; then
echo "a >= b"
fi
Logical Operators
| Operator | Description |
|---|---|
! expr | NOT |
expr -a expr | AND |
expr -o expr | OR |
Examples
# NOT
if [ ! -f "$file" ]; then
echo "File not found"
fi
# AND
if [ -f "$file" -a -r "$file" ]; then
echo "File exists and is readable"
fi
# OR
if [ -z "$a" -o -z "$b" ]; then
echo "At least one is empty"
fi
Combining with && and ||
# Preferred over -a and -o
if [ -f "$file" ] && [ -r "$file" ]; then
echo "File exists and readable"
fi
if [ -z "$a" ] || [ -z "$b" ]; then
echo "At least one is empty"
fi
Common Patterns
Check File Exists
if [ -f "$config" ]; then
source "$config"
fi
Check Directory
if [ ! -d "$dir" ]; then
mkdir -p "$dir"
fi
Validate Arguments
if [ $# -eq 0 ]; then
echo "Usage: $0 file" >&2
exit 1
fi
Compare Strings
if [ "$answer" = "yes" ]; then
proceed
fi
Numeric Comparison
if [ $count -gt 100 ]; then
echo "Too many items"
fi
Important Notes
Spaces Required
# Wrong
if [-f "$file"]; then
# Correct
if [ -f "$file" ]; then
Quote Variables
# Wrong (breaks if file has spaces)
if [ -f $file ]; then
# Correct
if [ -f "$file" ]; then
= vs ==
In POSIX shell, use = for string comparison:
# POSIX compliant
if [ "$a" = "$b" ]; then
# Also works but less portable
if [ "$a" == "$b" ]; then
Operators & Redirection
Hash shell supports Unix operators for connecting and controlling commands.
Overview
| Operator | Type | Description |
|---|---|---|
| | Pipe | Connect stdout to stdin |
> | Redirect | Output to file (overwrite) |
>> | Redirect | Output to file (append) |
< | Redirect | Input from file |
2> | Redirect | Stderr to file |
&> | Redirect | Both stdout and stderr |
&& | Chain | Run if previous succeeded |
|| | Chain | Run if previous failed |
; | Chain | Run sequentially |
& | Background | Run in background |
Quick Examples
Pipes
ls | grep txt
cat file.txt | sort | uniq
ps aux | grep nginx | wc -l
Redirection
echo "Hello" > file.txt # Overwrite
echo "World" >> file.txt # Append
cat < input.txt # Input from file
command 2> errors.log # Stderr
command &> all.log # Both
Command Chaining
make && make install # Run if success
cd /nonexistent || echo "Failed" # Run if fail
echo "Start"; command; echo "End" # Sequential
Background
long_command & # Run in background
Learn More
- Pipes - Connect command output to input
- I/O Redirection - Control file input/output
- Command Chaining - Sequential and conditional execution
- Command Substitution - Use command output as arguments
- Background Processes - Run commands in background
Pipes
Connect the output of one command to the input of another.
Basic Usage
#> ls | grep txt
file1.txt
test.txt
#> cat file.txt | grep pattern | sort | uniq
How Pipes Work
command1 | command2 | command3
command1stdout →command2stdincommand2stdout →command3stdincommand3stdout → terminal
Each command runs in its own process.
Exit Code
Pipeline exit code is from the last command:
#> false | true
#> echo $?
0 # From 'true', not 'false'
Common Patterns
Filtering
ls -la | grep txt
ps aux | grep nginx
cat log.txt | grep error
Counting
ls | wc -l # Count files
cat file.txt | wc -l # Count lines
ps aux | grep python | wc -l # Count processes
Text Processing
cat names.txt | sort | uniq
ls -la | awk '{print $5, $9}'
echo hello | tr '[:lower:]' '[:upper:]'
Data Analysis
cat data.csv | cut -d, -f2 | sort | uniq -c | sort -rn | head -10
With Other Features
With Aliases
alias count='wc -l'
ls | count
With Variables
export PATTERN=error
cat log.txt | grep $PATTERN
With Chaining
ls | grep txt && echo "Found txt files"
Difference from ||
| Operator | Purpose |
|---|---|
| | Connect stdout to stdin |
|| | Execute if previous failed |
echo hello | cat # Pipe: passes "hello" to cat
false || echo hello # OR: runs echo because false failed
Troubleshooting
Broken Pipe
If first command produces lots of output but second exits early:
cat huge_file.txt | head -10
# Normal behavior, handled automatically
No Output / Hanging
Command waiting for input:
cat | grep something
# Waiting forever - press Ctrl+C
Limitations
- No
|&(pipe stderr) - No process substitution
<(command)
I/O Redirection
Control where commands read from and write to.
Basic Redirections
Output (>)
Redirect stdout to file (overwrites):
echo "Hello" > output.txt
ls -la > filelist.txt
Append (>>)
Append to file:
echo "Line 1" > log.txt
echo "Line 2" >> log.txt
Input (<)
Read from file:
cat < input.txt
wc -l < file.txt
sort < unsorted.txt > sorted.txt
Here-Documents (<<)
The lines up to the delimiter become the command’s input. Variables and command
substitutions in the body are expanded unless the delimiter is quoted; <<-
also strips leading tabs, so the body can be indented with the code around it:
cat <<EOF
Hello, $USER
EOF
cat <<'EOF'
$USER is printed as written
EOF
if true; then
cat <<-EOF
indented with a tab, printed flush left
EOF
fi
Error Redirection
Stderr (2>)
ls /nonexistent 2> errors.txt
command 2>> errors.log # Append
Stderr to Stdout (2>&1)
command 2>&1 | grep error
make 2>&1 | tee build.log
Both Streams (&>)
command &> all.log
# Same as: command > all.log 2>&1
Common Patterns
Discard Output
command > /dev/null # Discard stdout
command 2> /dev/null # Discard stderr
command &> /dev/null # Discard both
Logging
./script.sh &> script.log
./daily.sh &>> daily.log # Append
Separate Streams
command > output.txt 2> errors.txt
Processing Files
tr '[:lower:]' '[:upper:]' < input.txt > output.txt
sort < data.txt > sorted.txt
Order Matters
# Both to file
command > file 2>&1
# Both to pipe
command 2>&1 | grep error
File Descriptors
0= stdin1= stdout2= stderr
2> file # Redirect fd 2
1> file # Same as > file
0< file # Same as < file
Troubleshooting
Permission Denied
Check file/directory permissions.
Accidental Overwrite
Use >> to append, or check first:
test -f file.txt && echo "File exists!"
Noclobber
set -C (set -o noclobber) makes > refuse to overwrite an existing file;
>| overwrites anyway. See the shell options.
Limitations
- No here-string (
<<< "string") - No process substitution (
<(command))
Command Chaining
Execute multiple commands with conditional or sequential logic.
Operators
| Operator | Name | Behavior |
|---|---|---|
&& | AND | Run next if previous succeeded (exit 0) |
|| | OR | Run next if previous failed (exit non-0) |
; | Sequential | Run next regardless |
AND (&&)
Run second command only if first succeeds:
make && make install
# make install runs only if make succeeds
cd /project && npm install
# npm install runs only if cd succeeds
mkdir -p dir && cd dir && touch file
# Creates dir, enters it, creates file
OR (||)
Run second command only if first fails:
cd /nonexistent || echo "Directory not found"
# echo runs because cd failed
command || exit 1
# Exit script if command fails
test -f config || cp default.conf config
# Copy default only if config doesn't exist
Sequential (;)
Run commands in sequence regardless of exit codes:
echo "Start"; command; echo "End"
# All three run
cd /tmp; ls; pwd
# All run even if one fails
Combined Patterns
Build and Install
make clean && make && make install
Create If Not Exists
test -d "$dir" || mkdir -p "$dir"
Try Multiple Options
command1 || command2 || command3
# Tries each until one succeeds
Fallback with Message
./run.sh || echo "Script failed" && exit 1
Grouped Commands
(cd /project && make) || echo "Build failed"
Exit Codes
AND Chain
true && echo "runs" # runs
false && echo "skipped" # skipped
OR Chain
true || echo "skipped" # skipped
false || echo "runs" # runs
Chain Exit Code
Exit code is from the last executed command:
true && false
echo $? # 1 (from false)
false || true
echo $? # 0 (from true)
Common Use Cases
Safe Directory Operations
cd /some/dir && rm -rf temp/
# Only deletes if cd succeeds
Conditional Execution
[ -f config.yml ] && source config.yml
Error Handling
command || { echo "Error" >&2; exit 1; }
Cleanup on Success
make && make test && make clean
With Other Features
With Pipes
cat file | grep pattern && echo "Found"
make 2>&1 | tee log && echo "Success"
With Redirection
command > output && echo "Saved"
With Variables
export DEBUG=1 && ./run.sh
Command Substitution
Use command output as part of another command.
Syntax
$(…) - Modern Syntax (Recommended)
result=$(command)
echo "Today is $(date)"
`…` - Backtick Syntax
result=`command`
echo "Today is `date`"
The $(...) syntax is preferred as it’s easier to nest and read.
Basic Usage
Capture Output
current_dir=$(pwd)
echo "You are in: $current_dir"
file_count=$(ls | wc -l)
echo "Files: $file_count"
In Commands
echo "Today is $(date)"
# Today is Mon Jan 1 12:00:00 UTC 2024
cd $(dirname "$0")
# Change to script's directory
In Variables
VERSION=$(cat VERSION)
HOSTNAME=$(hostname)
USER_HOME=$(eval echo ~$USER)
Common Patterns
Get Current Date/Time
NOW=$(date +%Y%m%d)
TIMESTAMP=$(date +%H%M%S)
Count Items
NUM_FILES=$(ls *.txt | wc -l)
NUM_LINES=$(wc -l < file.txt)
Find Commands
EDITOR=$(which vim)
GIT_ROOT=$(git rev-parse --show-toplevel)
Process Output
for file in $(find . -name "*.txt"); do
echo "Processing: $file"
done
for user in $(cat /etc/passwd | cut -d: -f1); do
echo "User: $user"
done
Nesting
The $(...) syntax allows easy nesting:
echo "Script dir: $(dirname $(realpath $0))"
# With backticks (harder to read)
echo "Script dir: `dirname \`realpath $0\``"
In Arithmetic
total=$(($(cat file1 | wc -l) + $(cat file2 | wc -l)))
With Quoting
# Preserve whitespace
files="$(ls -la)"
echo "$files"
# Word splitting (each line becomes argument)
for line in $(cat file.txt); do
echo "$line"
done
Exit Codes
Command substitution captures output, not exit code:
result=$(false)
echo $? # 1 (exit code available immediately after)
# Check both
if output=$(command); then
echo "Success: $output"
else
echo "Failed"
fi
Examples
Backup with Date
backup_file="backup_$(date +%Y%m%d).tar.gz"
tar -czf "$backup_file" /data
Dynamic Paths
cd "$(git rev-parse --show-toplevel)"
source "$(dirname $0)/config.sh"
Conditional on Output
if [ "$(whoami)" = "root" ]; then
echo "Running as root"
fi
Build Version String
VERSION="$(cat VERSION)-$(git rev-parse --short HEAD)"
Limitations
- Trailing newlines are stripped
- Very large output may be slow
- Exit code only available immediately after
Background Processes
Run commands in the background while continuing to use the shell.
Basic Usage
Add & at the end of a command:
#> long_running_command &
[1] 12345
#>
The shell prints:
- Job number in brackets
[1] - Process ID
12345 - Returns to prompt immediately
Job Control
List Jobs
#> jobs
[1] Running sleep 100 &
[2] Running make &
Bring to Foreground
#> fg %1
# Job 1 now in foreground
Send to Background
#> bg %1
# Continues job 1 in background
Stopping Jobs
Kill by Job Number
#> kill %1
Kill by PID
#> kill 12345
Job Completion
When a background job completes:
[1] Done sleep 10 &
Common Patterns
Run Long Command
make &
# Continue working while make runs
Multiple Background Jobs
command1 &
command2 &
command3 &
# All three run simultaneously
Redirect Output
long_command > output.log 2>&1 &
# Run in background, save output to file
Discard Output
noisy_command &> /dev/null &
Background Process Behavior
stdin
Background processes have stdin disconnected from terminal:
cat &
# Will receive EOF immediately
Signals
Background processes:
- Ignore
SIGINT(Ctrl+C) - Receive
SIGHUPwhen shell exits (unless usingnohup)
Exit Warning
When exiting with running jobs:
#> exit
hash: There are running jobs.
#> exit
# Second exit forces quit
Practical Examples
Build While Working
make clean && make &
# Edit files while building
Download in Background
curl -O http://example.com/large-file.zip &
Run Server
python -m http.server 8000 &
Watch Logs
tail -f /var/log/syslog &
Tips
Check if Job Running
jobs
# or
ps aux | grep command
Wait for Completion
command &
pid=$!
# Do other work...
wait $pid
echo "Command finished"
Nohup for Persistent Jobs
For jobs that should survive logout:
nohup long_command &
# Output goes to nohup.out
Limitations
- Job control is basic compared to bash
- No
disowncommand - No sophisticated job status tracking
Quick Reference
A consolidated reference for hash shell features.
Command Line Options
| Option | Description |
|---|---|
-c string | Execute commands from string |
-i | Force interactive mode |
-l, --login | Run as login shell |
-s | Read from stdin |
-a -b -C -e -f -m -n -u -x | Shell options, as for set |
-v, --version | Print version |
-h, --help | Show help |
Key Bindings
Navigation
| Key | Action |
|---|---|
Left/Right | Move cursor |
Up/Down | History navigation |
Ctrl+A | Beginning of line |
Ctrl+E | End of line |
Home/End | Beginning/End of line |
Editing
| Key | Action |
|---|---|
Backspace | Delete before cursor |
Delete | Delete at cursor |
Ctrl+U | Delete to beginning |
Ctrl+K | Delete to end |
Ctrl+W | Delete word |
Ctrl+H | Same as Backspace |
Other
| Key | Action |
|---|---|
Tab | Auto-complete |
Ctrl+L | Clear screen |
Ctrl+C | Cancel line |
Ctrl+D | EOF / Exit |
Enter, Ctrl+J | Run the line |
set -o vi switches to vi mode; set -o emacs is the default.
Operators
| Operator | Description |
|---|---|
| | Pipe stdout to stdin |
> | Output to file (overwrite) |
>> | Output to file (append) |
< | Input from file |
2> | Stderr to file |
&> | Both stdout and stderr |
2>&1 | Stderr to stdout |
&& | Run if previous succeeded |
|| | Run if previous failed |
; | Run sequentially |
& | Run in background |
Special Variables
| Variable | Description |
|---|---|
$? | Exit code of last command |
$$ | Shell process ID |
$0 | Shell/script name |
$1-$9 | Positional arguments |
$# | Number of arguments |
$@ | All arguments (separate) |
$* | All arguments (single) |
$- | Option letters in effect |
$LINENO | Current line number |
Test Operators
File Tests
| Test | Description |
|---|---|
-e | Exists |
-f | Regular file |
-d | Directory |
-r | Readable |
-w | Writable |
-x | Executable |
-s | Size > 0 |
-L | Symbolic link |
String Tests
| Test | Description |
|---|---|
-z | Empty string |
-n | Non-empty string |
= | Equal |
!= | Not equal |
Numeric Tests
| Test | Description |
|---|---|
-eq | Equal |
-ne | Not equal |
-lt | Less than |
-le | Less or equal |
-gt | Greater than |
-ge | Greater or equal |
PS1 Escape Sequences
set prompt=NAME picks a preset: classic, plain, minimal, two-line, powerline; set prompt=list shows them. PS1 builds your own (Prompt Customization):
| Sequence | Description |
|---|---|
\w | Full path |
\W | Current directory |
\u | Username |
\h | Hostname, up to the first dot |
\H | Full host name |
\g | Git branch + status |
\b | Git branch alone, nothing outside a repository |
\e | Exit code color, between \e...\e |
\? | Last exit status when it was not 0 |
\$ | $ or # for root |
\t \T \@ | Time: 24-hour, 12-hour, 12-hour with am/pm |
\d | Date |
\j | Number of background jobs |
\! | History number of the next command |
\s \v | Shell name and version |
\n | Newline |
\\ | A backslash |
\[ \] | Ignored (bash’s colour-code brackets) |
History Expansion
| Pattern | Description |
|---|---|
!! | Last command |
!n | Command number n |
!-n | n commands ago |
!prefix | Last starting with prefix |
Environment Variables
| Variable | Description |
|---|---|
HISTSIZE | Commands in memory |
HISTFILESIZE | Commands in file |
HISTFILE | History file location |
FUNCNEST | Function nesting limit, eval and . included (default 1000; 0 keeps only the stack guard) |
HISTCONTROL | History behavior |
PS1 | Prompt format |
PS2 | Continuation prompt |
PS4 | Prefix of set -x lines |
PATH | Command search path |
HOME | Home directory |
EDITOR | Default editor |
Shell Options
Set with set -x, clear with set +x; cluster letters (set -ex) or use the
name (set -o xtrace). set -o alone lists them, set +o prints them as
commands, and $- holds the letters in effect.
| Letter | Name | Effect |
|---|---|---|
-a | allexport | Every assignment is exported |
-b | notify | Accepted; background job status is reported at the prompt |
-C | noclobber | > does not overwrite an existing file (`> |
-e | errexit | Exit when a command fails |
-f | noglob | No pathname expansion |
-h | Accepted; commands are remembered as they run | |
-m | monitor | Job control |
-n | noexec | Read and parse commands without running them (not at the prompt) |
-u | nounset | Expanding an unset variable is an error |
-v | verbose | Print input lines as they are read |
-x | xtrace | Print each command, after expansion, before it runs (PS4 is the prefix) |
nolog | Keep commands out of the history | |
nonlexicalctrl | break and continue reach loops in calling functions | |
emacs | Emacs-style line editing (the default) | |
vi | Vi-style modal line editing; set -o vi turns emacs off and back |
hash’s own set name=value options (prompt, colors, welcome, PS1, color.<element>,
syntax_highlight, autosuggest, danger_highlight) are listed on the
configuration page.
Built-in Commands
The Built-in Commands page has the full entry for each, the text help NAME prints; this table is the one-line form. Every builtin takes -- as the end of its options.
| Command | Synopsis and meaning |
|---|---|
: | : [arg...]: do nothing, status 0 |
., source | . file, source file: run a file in the current shell |
[, test | [ expr ], test expr: evaluate an expression (Test Command) |
[[ | [[ expr ]]: extended test, with ==/!= patterns, =~ regular expressions, && and || inside |
alias | alias [name[=value]...]: define or print aliases |
bg | bg [%job]: continue a stopped job in the background |
break | break [n]: leave n enclosing loops |
cd | cd [-L|-P] [dir]: change directory; -L (default) keeps the logical path, -P resolves symlinks, cd - goes back |
command | command name [arg...], command -v | -V name...: run a command without function lookup; -v/-V show how a name resolves |
complete | complete [-abcdfuv] [-o default|dirnames] [-W words] [-F function] name..., complete -p [name...], complete -r [name...]: programmable completion |
continue | continue [n]: next iteration of n enclosing loops |
echo | echo [-neE] [arg...]: print the arguments |
eval | eval [arg...]: run the arguments as a command |
exec | exec [command [arg...]], exec redirection...: replace the shell, or redirect it for good |
exit | exit [n]: leave the shell |
export | export [-p] [name[=value]...]: put variables in the environment; -p prints them |
false | false: status 1 |
fg | fg [%job]: bring a job to the foreground |
getopts | getopts optstring name [arg...]: parse options in a script |
hash | hash [-r] [name...]: remember where commands live; -r forgets |
help | help [-s] [pattern...]: synopsis and description of builtins and keywords; -s synopsis only |
history | history [-c | -w | -r]: show the history; clear it, write or read the file |
jobs | jobs [-l | -p]: list background jobs, with pids, or pids only |
kill | kill [-s signal | -signal] pid | %job ..., kill -l: send a signal; -l lists the names |
local | local [name[=value]...]: variables local to a function |
logout | logout: leave a login shell |
pwd | pwd [-L|-P]: print the working directory, logical or physical |
read | read [-r] name...: read a line into variables, split on IFS; -r keeps backslashes |
readonly | readonly [-p] [name[=value]...]: make variables read-only; -p prints them |
return | return [n]: return from a function or sourced file |
set | set [-abCefhmnuvx] [-o option] [+...] [--] [arg...], set name=value: shell options and positional parameters, and hash’s own settings (Shell Options) |
shift | shift [n]: drop positional parameters |
times | times: user and system times of the shell and its children |
trap | trap [action] [signal...], trap -l | -p: run commands on signals and at EXIT; -l lists the signals, -p prints the traps |
true | true: status 0 |
type | type [-afptP] name...: how a name would be interpreted; -t one word, -p/-P the file, -a every match, -f no functions |
ulimit | ulimit [-HS] [-a | -cdfnstuv] [limit]: show or set resource limits |
umask | umask [-S] [mode]: show or set the file creation mask; -S symbolic |
unalias | unalias [-a] name...: remove aliases; -a all of them |
unset | unset [-f | -v] name...: remove variables (-v) or functions (-f) |
update | update: install a newer release of hash when there is one |
wait | wait [pid | %job ...]: wait for background jobs |
Configuration Files
| File | When Loaded |
|---|---|
/etc/profile | Login shell |
~/.hash_profile | Login shell |
~/.profile | Login shell (fallback) |
~/.hashrc | Interactive shell |
~/.hash_logout | Login shell exit |
Built-in Commands
The 44 builtins, as help lists them in the shell; help NAME prints one entry.
Every builtin takes -- as the end of its options. The quick reference
has the one-line form.
.
. file
Read and run file in the current shell (POSIX spelling of source). return ends the file; exit ends the shell.
:
: [arg...]
Do nothing; the arguments are expanded and dropped. Status 0.
[
[ expr ]
The test command written with brackets; the closing ] is required. See help test for the operators.
More: test command
[[
[[ expr ]]
Extended test: the operators of test plus pattern matching with == and !=, regular expressions with =~, and && and || inside the brackets. Words are not split or glob-expanded.
More: test command
alias
alias [name[=value]...]
Define aliases, or print them: alias lists every alias, alias name prints one. An alias is expanded when its name is the first word of a command.
More: hashrc
bg
bg [%job]
Continue a stopped job in the background.
More: background
break
break [n]
Leave the innermost n enclosing loops (one by default).
cd
cd [-L|-P] [dir]
Change the working directory to dir, or to $HOME without one. -L, the default, keeps the logical path, so cd .. under a symlinked directory goes to the parent of the link; -P follows symlinks and sets PWD to the physical path. cd - goes back to the previous directory and prints it. PWD and OLDPWD are updated.
command
command name [arg...]
command -v | -V name...
Run name without looking up functions, so a function can call the command it shadows; a failing special builtin does not end the shell, but break, continue, return and exit keep their effect. -v prints how name would be resolved, -V describes it.
complete
complete [-abcdfuv] [-o default|dirnames] [-W words] [-F function] name...
complete -p [name...]
complete -r [name...]
Record how a command’s arguments are tab-completed. -W gives the candidate words, -F a function whose output lines are candidates ($1 command, $2 word, $3 previous word), -a -b -c -d -f -u -v add aliases, builtins, commands, directories, files, users or variables, -o default falls back to files. -p prints the definitions in a form that can be typed back, -r removes them.
More: tab completion
continue
continue [n]
Resume the next iteration of the innermost n enclosing loops.
echo
echo [-neE] [arg...]
Print the arguments separated by spaces, then a newline. -n leaves out the newline, -e interprets backslash escapes (\n \t \ …), -E does not.
eval
eval [arg...]
Join the arguments with spaces and run the result as a command in the current shell.
exec
exec [command [arg...]]
exec redirection...
Replace the shell with command. With only redirections, apply them to the shell itself for the commands that follow (exec 3< file, exec >log).
More: redirection
exit
exit [n]
Leave the shell with status n, or with the status of the last command. The EXIT trap runs first; a login shell also runs ~/.hash_logout.
export
export [-p] [name[=value]...]
Mark variables for export to the environment of commands, assigning a value when one is given. -p, or no arguments, prints the exported variables.
false
false
Do nothing, with status 1.
fg
fg [%job]
Bring a job to the foreground and wait for it. Without an argument, the current job.
More: background
getopts
getopts optstring name [arg...]
Parse options from the positional parameters (or arg…) one call at a time, placing the letter in name, its argument in OPTARG and the next index in OPTIND. A colon after a letter in optstring means it takes an argument; a leading colon selects silent error reporting.
hash
hash [-r] [name...]
Remember where commands live. With names, look them up now; -r forgets everything remembered; alone, print the table.
help
help [-s] [pattern...]
Describe the builtins and the shell’s keywords. Alone, list every topic with its synopsis; with names or glob patterns, print the synopsis and a short description of each; -s prints the synopsis only. The book has the same text at https://hash-shell.org/reference/builtins.html
history
history [-c | -w | -r]
Print the command history with its numbers. -c clears it, -w writes it to the history file, -r reads the file back. HISTFILE, HISTSIZE, HISTFILESIZE and HISTCONTROL apply; !!, !n, !-n and !prefix expand entries.
More: history
jobs
jobs [-l | -p]
List the background jobs of this shell. -l adds the process IDs, -p prints only them.
More: background
kill
kill [-s signal | -signal] pid | %job ...
kill -l
Send a signal (TERM by default) to processes or jobs, by number or name. -l lists the signal names.
More: background
local
local [name[=value]...]
Declare variables local to the current function; the previous values come back when it returns. Outside a function it is an error.
More: index
logout
logout
Leave a login shell, running ~/.hash_logout first. In a shell that is not a login shell it fails; use exit.
pwd
pwd [-L|-P]
Print the working directory. -L (the default) prints $PWD, the path cd built, when it still names the current directory; -P prints the physical path with every symbolic link resolved.
read
read [-r] name...
Read one line from standard input and split it into the variables; the last one takes the rest. Backslash continues a line unless -r is given. The status is 1 at end of input.
readonly
readonly [-p] [name[=value]...]
Mark variables read-only, assigning a value when one is given; later assignments and unset fail. -p, or no arguments, prints them.
return
return [n]
Leave the current function or sourced file with status n, or with the status of the last command.
More: index
set
set [-abCefhmnuvx] [-o option] [+...] [--] [arg...]
set name=value
Set shell options with -, clear them with +: -a allexport, -b notify, -C noclobber, -e errexit, -f noglob, -h, -m monitor, -n noexec, -u nounset, -v verbose, -x xtrace; -o takes a name, also emacs, vi, nolog and nonlexicalctrl. set -o lists the options, set +o prints them as commands, $- holds the letters in effect. Arguments after the options (or after –) become the positional parameters. hash’s own settings use name=value: prompt=NAME picks a prompt preset (classic, plain, minimal, two-line, powerline; prompt=list shows them), PS1=… builds one, and colors=on|off, welcome=on|off, color.
More: index
shift
shift [n]
Drop the first n positional parameters (one by default). A count past $# is an error.
source
source file
Read and run file in the current shell, like .. Functions, variables and aliases it defines stay. A file name without a slash is looked up in PATH.
test
test expr
Evaluate a conditional expression: file tests (-e -f -d -r -w -x -s -L and more), string tests (-z -n = !=), numbers (-eq -ne -lt -le -gt -ge), and ! -a -o with parentheses. The status is 0 when expr is true. [ expr ] is the same command with a closing bracket.
More: test command
times
times
Print the user and system times used by the shell and by its children.
trap
trap [action] [signal...]
trap -l | -p
Run action when a signal arrives, or at EXIT. An empty action ignores the signal, - restores the default. -l lists the signal names, -p prints the traps in effect. The EXIT trap sees the shell’s status as $?.
true
true
Do nothing, successfully.
type
type [-afptP] name...
Say how each name would be interpreted: an alias, a shell keyword, a function, a builtin, or a file found in PATH, in that order. -t prints one word (alias, keyword, function, builtin, file); -p prints the file that would run and nothing for anything else; -P searches PATH even when an alias, function or builtin would run; -a prints every match; -f skips functions. Status 1 when a name is not found.
ulimit
ulimit [-HS] [-a | -cdfnstuv] [limit]
Show or set a resource limit of the shell and the commands it runs. -c core file (512-byte blocks), -d data (KB), -f file size (blocks), -n open files, -s stack (KB), -t CPU seconds, -u processes, -v virtual memory (KB); -f when no resource is named. -a shows them all. -H acts on the hard limit, -S on the soft one (both when setting, the soft one when showing). The limit is a number or unlimited.
umask
umask [-S] [mode]
Show or set the file creation mask. Without a mode, print it in octal, or with -S as u=rwx,g=rx,o=rx. A mode is octal (022) or symbolic (u+r, g-w,o=, a=rx) as for chmod.
unalias
unalias [-a] name...
Remove the named aliases, or every alias with -a. A name that is not an alias is reported and the status is 1; the other names are still removed.
More: hashrc
unset
unset [-f | -v] name...
Remove variables (-v, the default) or functions (-f). Readonly variables cannot be unset.
update
update
Check for a newer release of hash and install it when one is available. HASH_DISABLE_UPDATE_CHECK=1 turns the startup check off.
wait
wait [pid | %job ...]
Wait for the given background jobs, or for all of them, and return the status of the last one waited for.
More: background
Contributing Guide
Thank you for your interest in contributing to hash!
Getting Started
Prerequisites
- GCC or Clang compiler
- Make build system
- Git
Fork and Clone
git clone https://github.com/YOUR_USERNAME/hash.git
cd hash
git remote add upstream https://github.com/juliojimenez/hash.git
Build
make clean
make
./hash-shell
Debug Build
make debug
Project Structure
hash/
├── src/ # Source files
│ ├── main.c # Entry point
│ ├── hash.h # Main header
│ ├── parser.c/h # Command parsing
│ ├── execute.c/h # Execution
│ ├── builtins.c/h # Built-in commands
│ ├── history.c/h # Command history
│ ├── completion.c/h # Tab completion
│ ├── lineedit.c/h # Line editing
│ ├── prompt.c/h # Prompt generation
│ └── ...
├── tests/ # Unit tests
├── docs/ # Documentation
├── book/ # Book of Hash source
└── Makefile
Coding Standards
Style
- 4 spaces indentation (no tabs)
- Functions:
snake_casewith module prefix - Constants:
UPPER_SNAKE_CASE - Max line length: 100 characters
int example_function(char *arg) {
if (arg == NULL) {
return -1;
}
return 0;
}
Safe String Functions
Always use safe string functions:
// Good
safe_strcpy(dst, src, sizeof(dst));
safe_strcat(dst, src, sizeof(dst));
// Avoid
strcpy(dst, src); // No bounds checking
strcat(dst, src); // No bounds checking
Compiler Warnings
Code must compile cleanly:
gcc -Wall -Wextra -Werror -std=gnu99
Testing
Setup Test Framework
make test-setup
Run Tests
make test # Unit tests
./test.sh # Integration tests
Writing Tests
Tests use Unity framework:
#include "unity.h"
void test_feature_works(void) {
int result = function("input");
TEST_ASSERT_EQUAL_INT(0, result);
}
int main(void) {
UNITY_BEGIN();
RUN_TEST(test_feature_works);
return UNITY_END();
}
Submitting Changes
Branch Naming
feature/description- New featuresfix/description- Bug fixesdocs/description- Documentation
Commit Messages
type(scope): description
Types: feat, fix, docs, style, refactor, test, chore
Examples:
feat(completion): add environment variable completion
fix(history): prevent duplicate entries
docs(readme): update installation instructions
Before Submitting
# Sync with upstream
git fetch upstream
git rebase upstream/main
# Run tests
make clean && make && make test
./test.sh
# Check warnings
make CFLAGS="-Wall -Wextra -Werror -std=gnu99"
Pull Request
- Push branch to your fork
- Open PR against
juliojimenez/hash:main - Fill out PR template
- Address review feedback
Getting Help
- Questions: GitHub Discussions
- Bugs: GitHub Issues
- Email: julio@julioj.com
Testing
Hash uses the Unity test framework for unit tests, a shell script for integration tests, and a small Python driver that types at the shell in a pseudo-terminal for interactive tests.
Setup
Download the Unity framework (first time only):
make test-setup
Running Tests
Unit Tests
make test
Integration Tests
./test.sh
Interactive Tests
python3 tests/interactive/run.py
Conformance Suites
bash tests/modernish/run.sh # modernish, compared with tests/modernish/baseline.txt
The smoosh suite runs in CI only (.github/workflows/posix.yml); running all of it locally exhausts the process limit.
Clean Test Artifacts
make test-clean
Writing Unit Tests
Test File Structure
Create tests/test_module.c:
#include "unity.h"
#include "../src/module.h"
void setUp(void) {
// Setup before each test
}
void tearDown(void) {
// Cleanup after each test
}
void test_feature_works(void) {
int result = module_function("input");
TEST_ASSERT_EQUAL_INT(0, result);
}
void test_handles_null(void) {
int result = module_function(NULL);
TEST_ASSERT_EQUAL_INT(-1, result);
}
int main(void) {
UNITY_BEGIN();
RUN_TEST(test_feature_works);
RUN_TEST(test_handles_null);
return UNITY_END();
}
Common Assertions
TEST_ASSERT_EQUAL_INT(expected, actual)
TEST_ASSERT_EQUAL_STRING(expected, actual)
TEST_ASSERT_NOT_NULL(pointer)
TEST_ASSERT_NULL(pointer)
TEST_ASSERT_TRUE(condition)
TEST_ASSERT_FALSE(condition)
Integration Tests
Add tests to test.sh:
run_test "description" "command" "expected_output"
run_command_test "description" "command"
run_file_test "description" "command" "file" "expected"
Interactive Tests
tests/interactive/run.py runs the shell in a pseudo-terminal and types at it, so the line editor, the continuation prompt, Ctrl-C, Ctrl-R, the startup files and the history file are tested the way a user meets them. Piping into hash-shell -i cannot reach those paths.
Each case is a text file in tests/interactive/cases/, one directive per line:
# Ctrl-C at the continuation prompt abandons the unfinished compound command
send if true; then
expect ...
send echo DIS''CARDED
raw \x03
expect ^C
send echo AF''TER
expect AFTER
absent DISCARDED
send exit
status 0
| Directive | Meaning |
|---|---|
send text | Wait for a prompt, type text, press Enter |
raw text | Send keystrokes as typed (\x03 is Ctrl-C, \r is Enter, \x1b[A is Up) |
expect text | Wait until text appears, after the previous match |
absent text | text must not have appeared so far |
wait seconds | Keep reading output for that long |
rc text / write FILE text | Add a line to ~/.hashrc or another file under the session’s HOME before the shell starts |
env NAME=value | Set a variable for the shell |
login | Start the shell as a login shell |
status N | The shell must exit with status N |
file FILE has text / lacks text | Check a file under HOME after the session |
Every case gets a fresh HOME, TERM=dumb, PS1="hash> " and PS2="... ", so expect ... is “the continuation prompt showed”. The shell echoes what is typed, so to check that a command did not run, type something whose output differs from its spelling: echo DIS''CARDED prints DISCARDED only if it ran.
python3 tests/interactive/run.py # every case
python3 tests/interactive/run.py ctrl-c -v # cases whose name contains ctrl-c, with their transcripts
python3 tests/interactive/run.py --keep # keep each case's HOME for a look
python3 tests/interactive/run.py --help # the full directive reference
Conformance Suites
Two external suites check hash against POSIX as other shells implement it.
smoosh (.github/workflows/posix.yml) is the gate: every push and pull request runs its 186 cases, and one is skipped on purpose (builtin.trap.subshell.false.exit, see the workflow for the reasoning). Run a subset locally rather than the whole suite, which exhausts the process limit.
modernish (.github/workflows/modernish.yml, tests/modernish/) is the second suite. It is not a gate: it runs weekly, on demand, and on changes to its own files, and fails only when the result is worse than tests/modernish/baseline.txt. bash tests/modernish/run.sh fetches modernish at the pinned commit, runs its regression suite as hash-shell bin/modernish --test -eq, prints the counts and compares them with the baseline; --update-baseline records an improvement. modernish refuses to start on a shell with any of the bugs in its fatal-bug battery, and hash has several of them today; tests/modernish/STATUS.md lists them with their issues and shows how to run the battery check by check.
Sanitizer Tests
AddressSanitizer
make clean
make CC=clang CFLAGS="-Wall -Wextra -O1 -g -fsanitize=address -fno-omit-frame-pointer -std=gnu99"
make test-clean
make test CC=clang CFLAGS="-Wall -Wextra -O1 -g -fsanitize=address -fno-omit-frame-pointer -std=gnu99"
UndefinedBehaviorSanitizer
make clean
make CC=clang CFLAGS="-Wall -Wextra -O1 -g -fsanitize=undefined -fno-omit-frame-pointer -std=gnu99"
make test-clean
make test CC=clang CFLAGS="-Wall -Wextra -O1 -g -fsanitize=undefined -fno-omit-frame-pointer -std=gnu99"
Combined (Most Thorough)
make clean
make CC=clang CFLAGS="-Wall -Wextra -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer -std=gnu99"
make test-clean
make test CC=clang CFLAGS="-Wall -Wextra -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer -std=gnu99"
Test Coverage Guidelines
When adding features:
- Write unit tests for all public functions
- Write integration tests for user-facing features
- Add an interactive case for anything a user sees or types at the prompt
- Test edge cases (NULL, empty strings, boundaries)
- Test error handling paths
Security Policy
Supported Versions
hash is developed fix-forward. Only the latest release is supported, and a security fix ships as a new release that includes it; earlier releases are not patched and nothing is backported. To receive security updates, upgrade to the latest release.
| Version | Supported |
|---|---|
| v54 (latest) | Yes |
| Earlier releases | No |
Reporting Vulnerabilities
Do NOT report security vulnerabilities through public issues.
Report via: Settings > Security > Advisories > New draft security advisory
Include:
- Type of vulnerability
- Affected source files
- Steps to reproduce
- Proof-of-concept (if possible)
- Impact assessment
Response Timeline
- Acknowledgment: 48 hours
- Initial Assessment: 7 days
- Resolution: 30 days (critical)
Security Best Practices
For Users
- Keep hash updated: earlier releases do not receive fixes
- Review .hashrc from untrusted sources
- Set proper permissions on config files (600)
- Use leading space for sensitive commands
For Contributors
- Use safe string functions (
safe_strcpy,safe_strcat) - Validate all array indices and buffer sizes
- Never trust user input
- Use reentrant functions (
getpwuid_rnotgetpwuid) - Free all allocated memory
- Keep the sanitizer and fuzzing workflows green
Security Features
Hash includes:
- Safe string utilities (bounds-checked)
- Input sanitization in parser
- History privacy (space prefix)
- No unsafe C functions (
gets,strcpy, etc.) - Stack protection (
-fstack-protector-strong) - Fortify source (
-D_FORTIFY_SOURCE=2)
Known Limitations
As a shell, hash executes arbitrary commands by design:
- Commands run with user privileges
- Aliases can execute arbitrary code
- Sourced scripts run in current context