LinuxCommandLibrary

hg-root

Find Mercurial repository's root directory

TLDR

Display the root location of the current repository

$ hg root
copy

Display the root location of the specified repository
$ hg root --cwd [path/to/directory]
copy

SYNOPSIS

hg root [options]

PARAMETERS

-R, --repository <repo>
    Repository root path or name (local dir or URL)

--cwd <dir>
    Change working directory before executing

DESCRIPTION

hg root (often invoked as hg-root in scripts or aliases) is a command from the Mercurial (hg) distributed version control system. It outputs the absolute path to the root directory of the current working repository, where the .hg control directory resides.

This command is invaluable for navigating large repositories from subdirectories. For instance, if your working directory is deep within a project tree like /repo/src/sub/module, running hg root simply prints /repo, enabling scripts to cd to the base or locate metadata files like .hg/hgrc.

If executed outside a repository, it fails silently with exit code 1 and no output, making it safe for conditional scripting (e.g., REPO_ROOT=$(hg root 2>/dev/null || echo .)). It traverses upward from the current directory until finding a valid repo or root filesystem.

Mercurial repositories are self-contained, and this command respects the --repository option for remote or alternate roots. Widely used in build systems, IDE integrations, and shell prompts for repo-aware paths.

CAVEATS

Fails (exit 1, no output) outside a repo. Ignores nested repos; reports nearest ancestor. Not for bare repos without .hg.

EXAMPLE

$ cd /path/to/repo/src
$ hg root
/path/to/repo

SCRIPT USAGE

REPO_ROOT="$(hg root)"
if [ -n "$REPO_ROOT" ]; then
  echo "In repo: $REPO_ROOT"
fi

HISTORY

Core Mercurial command since version 0.9b (January 2005). Evolved with repo formats; stable across all modern releases.

SEE ALSO

hg(1), hg identify(1), git rev-parse --show-toplevel(1)

Copied to clipboard