Skip to content

Latest commit

 

History

History
453 lines (338 loc) · 23.4 KB

navigation.md

File metadata and controls

453 lines (338 loc) · 23.4 KB

Navigation and Listing

The shell models Cosmos DB resources as a simple folder-like hierarchy under your connected account.

Resource Hierarchy

Account → Databases → Containers → Items

There are no folders inside a container – containers hold items (JSON documents) directly. Use ls to list the current level and cd to change scope. The pwd command prints the current location explicitly.

For a local Cosmos DB emulator connection (localhost or 127.0.0.1), the connection message shows the emulator endpoint and the prompt uses emulator instead of an account name, for example emulator > or emulator MyDb >.

Moving Around

doctor checks the current scope without navigating. Its --database and --container options select a diagnostic target only. An explicit database does not inherit the current container; specify both options to check another container. See doctor troubleshooting.

The ls Command

The ls command lists resources at the current level:

Context ls shows
Connected (root) All databases in the account
Inside a database All containers in that database
Inside a container Items (documents) in that container

Options:

Option Description
-m <n> Limit results to first n items (container scope). Default is 100 when omitted; use 0 or a negative value for no limit
-f <fmt> Output format (for example: table)
--db <name> Override database name
--con <name> Override container name
--key <prop> When listing items, match the filter against this item property (defaults to the container partition key property)

Examples:

ls                  # list current level; in a container this defaults to first 100 items
ls -m 10            # list first 10 items
ls -m 0             # list all matching items without a limit
ls "*active*" --key status
ls --db MyDb        # list containers in a specific database
ls --db MyDb --con Items -m 5

If ls reaches the effective limit while listing container items, it prints a runtime message telling you the results were limited.

Tip: to iterate local files in scripts, use dir:

for $script in (dir "examples/list_dir/*.csh") { echo $script.name }

The cd Command

The cd command changes your current scope:

From Command Result
Connected cd <database> Enter that database
Database cd <container> Enter that container
Any level cd .. Go up one level
Any level cd Return to connected (root) state

Path chaining:

You can chain path segments to navigate multiple levels at once:

cd MyDatabase/MyContainer    # enter database and container in one step
cd ../OtherContainer         # switch to sibling container
cd ../../OtherDb/OtherCont   # switch database and container

The Cosmos DB hierarchy has at most two levels (/database/container). Paths that resolve below that depth are rejected with an error. From inside a container, plain names like cd customers do not navigate to a sibling container. Use cd ../customers or a fully qualified absolute path such as cd /MyDatabase/customers.

Navigation patterns:

# Start from connected state
cd ToDoList                  # enter database
cd Items                     # enter container
ls -m 5                      # list first 5 items

# Quick switch between containers
cd ../Users                  # switch to Users container in same database
cd                           # return to root (connected state)

The pwd Command

The pwd command prints the current Cosmos DB location and the local working directory, including when disconnected:

pwd                  # Cosmos location: not connected
connect "AccountEndpoint=...;AccountKey=..."
pwd                  # Cosmos location: /
cd ToDoList
pwd                  # Cosmos location: /ToDoList
cd Items
pwd                  # Cosmos location: /ToDoList/Items

Each call also prints Local directory: <absolute path>, the base for relative paths used by commands such as export, import, and dir. Cosmos DB navigation with cd does not change it. Export success messages show the absolute destination path. For MCP, local paths refer to the machine running the shell server. Structured pwd results include this directory as localDirectory alongside the existing Cosmos location fields.

Reading an Item by ID

For point reads, print <id> <key> accepts the established typed-key syntax. Inside Cosmos DB Shell, print <id> 680 selects a number and print <id> '"680"' selects a string: outer shell quotes are removed, while the inner JSON quotes determine the key type. A complete hierarchical key is an ordered JSON array, for example print <id> '[1001,"customer-1001"]'. See print for examples and validation rules.

Pipes and JSON Flow

The | operator pipes the JSON result of the left command into the right command. This enables powerful command chaining.

Commands separated by a newline or ; do not implicitly pass results to the next command. For example, cd /db/items; rm safe-a --key=id --partition-key=p1 --dry-run previews the exact item, not the result of cd. Use | when you intend to pass input.

Explicit pipes within filter expressions also pass their own left-hand value to nested commands, for example echo [1] | filter '. | (filter ".")'.

Function and script calls follow the same rule, including empty bodies and bodies that only return a value. Explicit arguments are evaluated before the call's input is cleared.

How It Works

  1. Most commands return JSON – listings return a structured result like { "type": "<kind>", "values": [...] } (e.g. database, container, or item depending on context)
  2. The next command receives that JSON as its input
  3. Use JSON paths (starting with $) to extract values from piped JSON

JSON Path Syntax in Pipes

When a command receives piped JSON, you can use path expressions to access specific values:

Path Description
$ The entire piped JSON object
$.property Access a property
$.values[0] Access array element
.[0] Shorthand for first element (when result is array-like)

Practical Examples

Navigate to first database returned by ls:

ls | cd .[0]

Show the ID of the first item in current container:

ls -m 1 | echo $.values[0].id

Create multiple items from a JSON array:

echo '[{"id":"a","name":"Alice"},{"id":"b","name":"Bob"}]' | mkitem

Extract nested properties from arbitrary JSON:

echo '{"user":{"name":"Ada","email":"ada@example.com"}}' | echo $.user.name
# Output: Ada

Chain multiple operations:

# Get the first database, enter it, list containers
ls | cd .[0]; ls

Query and process results:

ls -q "SELECT c.id, c.status FROM c WHERE c.priority = 1" | echo $.values

Pipe-Aware Commands

These commands accept and process piped JSON:

Command Pipe behavior
mkitem Creates item(s) from piped JSON
replace Replaces existing item(s) using id and partition key from piped JSON
echo Outputs piped value or extracts path
cd Can use path to select target
delete Deletes item specified by piped JSON
filter Filters/transforms piped JSON with the native filter language (see filter and the filter v1 spec)
jq Filters/transforms piped JSON
ftab Formats piped JSON as table

Multi-line Input

The interactive prompt accepts commands that span more than one physical line. There are two ways to enter multi-line input — they can be mixed freely.

Automatic (parse-driven) continuation

The shell inspects what you've typed when you press Enter. If the input is syntactically incomplete, the prompt switches to a grey ... continuation prompt and keeps reading instead of executing. Input is considered incomplete when:

  • a block is left open: {, (, or [ without its matching close
  • a quoted string has no closing quote (", ', or interpolated `)
  • a statement ends part-way through (for example, after if, for, function, or a trailing operator)

Example — paste or type, pressing Enter at the end of each line:

> if ($x > 0) {
...     echo "positive"
... } else {
...     echo "non-positive"
... }

The command runs as soon as the final } closes the outer block.

Explicit backslash continuation

End any line with a single backslash (\) and press Enter to continue on the next line, bash-style. This works even when the input would parse on its own, which is useful for breaking long single-statement commands across lines:

> query "SELECT c.id, c.status FROM c \
... WHERE c.priority = 1" \
... --db ToDoList --con Items

Backslash runs follow normal escaping rules: an even number of trailing backslashes (\\, \\\\, …) is a literal and does not continue the line. An odd number (\, \\\, …) continues, with the final backslash consumed as the continuation marker.

Cancelling a multi-line entry

While the ... prompt is active:

  • Press Ctrl+C to discard everything you've typed so far and return to the regular prompt.
  • Press Esc to clear the current line; this only affects the line you're editing, not the buffered earlier lines.
  • An EOF / cancelled read (for example, Ctrl+D on an empty line) also discards the pending buffer.

There is no separate "enter multi-line mode" command — the shell enters and leaves continuation mode automatically based on the rules above.

History

Multi-line commands are saved to history as a single entry. When you recall one with Up / Ctrl+P or reverse-search (Ctrl+R), the full multi-line text is restored, with recognized credentials masked as described below. History formats written by older versions remain supported. Concurrent shells merge their saved entries into the shared history file. Saves and clears coordinate through cmd_history.lock and replace cmd_history only after the complete replacement has been written and flushed, so a failed write leaves the saved history intact. History saving remains best-effort; at most the newest 60 pending entries are retained for a later retry. A failed --clear-history reports an error and leaves the loaded history unchanged.

Recognized credentials, including connection-string AccountKey, SharedAccessKey, and ResourceToken values, are replaced with [REDACTED] in saved history. The endpoint and other non-secret connection settings remain available. This also applies to connection strings inside assignments, scripts, and multi-line history entries, including escaped credential names and values in string literals and object properties, named credential variables such as $AccountKey, and properties separated from their values by newlines or comments. Credential values containing interpolation expressions are masked in full. Non-secret interpolation expressions are preserved. Excessively nested quoted text is masked in full. Credential assignments and properties also mask grouped and combined value expressions, and bearer credentials with interpolation are masked as complete values. Ordinary query predicates on fields such as token, password, or secret are not treated as connection credentials. The command being executed is unchanged; to reuse a masked connection from history, supply a fresh key or use Entra ID.

Existing history entries are masked when loaded, and the next successful history save rewrites existing credentials on disk as well, including entries merged from another shell. Already-created backups or copies are not cleaned. This filter does not identify arbitrary secrets stored under unrelated names, so continue to treat cmd_history in the shell configuration directory as sensitive and do not share it. Use --clear-history to clear saved history.

Temporary history files have owner-only permissions on Unix. On Windows, they are created with the existing history file's access rules, or owner-only access for a new history file, without inheriting broader directory permissions; those rules remain on the published file. MCP tool invocations are echoed as command lines and recorded in the same history; redacting history does not mask the command echo or its output.

Keyboard Shortcuts

Run help shortcuts to see these shortcuts in the shell, grouped by History, Cursor Movement, Editing and Completion, and Shell. The help overview lists shortcuts under Help Topics. Structured results from help shortcuts include a keyboardShortcuts array with group, shortcut, and description fields, plus a historySearch note.

Available at the interactive prompt:

Shortcut Action
Up / Down Previous / next history entry
Ctrl+P / Ctrl+N Previous / next history entry
Ctrl+B / Ctrl+F Move cursor left / right
Tab / Ctrl+Tab Next / previous completion
Esc Clear current line
Ctrl+L Clear screen
Ctrl+A Move cursor to start of line
Ctrl+E Move cursor to end of line
Ctrl+U Delete text before cursor
Ctrl+K Delete text after cursor
Ctrl+W Delete previous word
Ctrl+D Exit shell when prompt is empty; otherwise delete character under cursor
Ctrl+R Reverse search history (type to filter, repeat for older matches, Enter accepts, Esc/Ctrl+G/Ctrl+C cancels)
Ctrl+S Forward search history (type to filter, repeat for newer matches, Enter accepts, Esc/Ctrl+G/Ctrl+C cancels)
Ctrl+C Interrupt running work or discard pending multi-line input

CLI Arguments

Start the shell with options to customize behavior:

Option Description
--output <format> Output format for command results: user (default interactive view), json, table, or csv. Alias: -o. Selecting json or csv enables machine mode. Falls back to COSMOSDB_SHELL_FORMAT.
--quiet Suppress informational messages, progress, banners, and command echoes. Preserve results, warnings, errors, and required authentication instructions. Enables machine mode. Alias: -q
-c <cmd> Execute command and exit. Everything after -c is taken as the command, so app-level options must come before -c. Windows-style /c is also accepted.
-k <cmd> Execute command and stay in shell. Everything after -k is taken as the command, so app-level options must come before -k. Windows-style /k is also accepted.
--connect <str> Connect with this connection string or endpoint on startup
--connect-mode <mode> Connection mode at startup: 'direct' or 'gateway'
--connect-tenant <id> Entra ID tenant ID at startup
--connect-hint <hint> Login hint for browser auth at startup
--connect-authority-host <url> Authority host URL at startup
--connect-managed-identity <id> User-assigned managed identity client ID at startup
--connect-subscription <id> Azure subscription ID for ARM database and container operations at startup
--connect-resource-group <name> Azure resource group name for ARM database and container operations at startup
--database <id> Navigate to this database after connecting at startup
--container <id> Navigate to this container after connecting at startup. Requires --database
--mcp [port] Enable MCP server with Streamable HTTP and legacy SSE on the given port, or 6128 by default
--diagnostics [path] Write timestamped diagnostic logs (commands, timing, errors, connection events) to a file, or to a timestamped file in the config directory by default
--otel [endpoint] Enable distributed tracing so requests carry a sampled W3C traceparent. Optionally export spans to an OTLP endpoint; falls back to the OTEL_EXPORTER_OTLP_ENDPOINT environment variable
--color-system <n> Color scheme: 0=off, 1=standard, 2=truecolor (alias: --cs)
--clear-history Clear command history on start
--help Show usage information
--version Show version

Machine Mode And Exit Codes

For automation and agentic wrappers, the shell can emit deterministic, machine-consumable output. Machine mode is entered when any of the following is true:

  • --output json or --output csv is specified (structured formats), or
  • --quiet is specified, or
  • -c is used without an explicit --output (defaults to json).

In machine mode the shell disables ANSI colors, suppresses connection/informational banners, emits command results as the selected structured format (JSON or CSV) on STDOUT, and writes parser, connection, and command failures (including theme errors and rejected non-interactive edit calls) as a structured { "status": "error", "error": ... } object on STDERR. In-shell 2> / 2>> redirection sends that error object to the specified file instead. STDOUT carries only the command result; tables and other interactive views are not rendered. Inferred partition-key mutation warnings are emitted before writes as JSON Lines records on console stderr; a later error is emitted as a separate JSON record. The human-facing user and table formats are not machine mode; user falls back to JSON whenever output is redirected, piped, or run in machine mode.

Quiet is not a universal mute: warnings, errors, and required instructions (such as authentication prompts and previews shown before a confirmation) remain visible on STDERR, without ANSI styling. Explicit diagnostic logging is unaffected. Command results are separate from informational messages and remain on STDOUT. Bulk-write errors include per-item diagnostics in that single structured error: imports identify source lines, and item-array writes identify 1-based item positions. Up to 100 item diagnostics are listed, followed by a count of any omitted ones. --verbose does not replace machine-mode errors with raw stack traces; shell 2> and 2>> redirection still applies and also captures warnings and required instructions. Outside machine mode, 2> and 2>> capture warnings and errors, while confirmation prompts and other required instructions stay on the terminal.

In normal user mode, command confirmations and status messages are readable text, not JSON status objects. Commands that display document or policy data can still show that data as JSON. Where supported, a command's --format / -f selects its result presentation and overrides the shell default. On import and export, it formats the summary, not file contents: a .csv export file name writes CSV and any other name writes a JSON array. Import automatically detects JSON arrays, single objects, and sequences of objects (including JSON Lines and multiple objects on one line); no input-format flag is needed.

Bare piped stdin (for example echo "..." | cosmosdbshell) is not implicitly machine mode; pass -c, --output json, or --quiet to opt into structured output.

Commands map failures to a stable set of exit codes (accessible via $?, %ERRORLEVEL%, or $LASTEXITCODE):

Exit code Meaning
0 Success
1 Generic error
2 Usage / bad arguments / parser or script syntax errors
3 Authentication or authorization failure (401/403, failed Entra credential)
4 Connection / network error (socket failure, timeout, 503)
5 Not found (404)
6 Throttled (429 / RU budget exceeded)

These values are a public contract. See the CI/CD guide for install steps, auth patterns, and scripted failure handling.

Usage errors (2) include missing or extra arguments, unknown command options, invalid option values, and rejected command input. For example, echo [1] | filter (missing expression), import sample.json --dry-run --concurrency 0, and echo [1] | ftab --format invalid return 2. Operational failures, such as a missing local input file or an editor failing to start, are not usage errors; service failures retain their status-specific exit codes above.

Ctrl+C interrupts commands started with -c, -k, or redirected stdin. An interrupted startup command returns a nonzero exit code and stops any following startup command; structured partial write results, including settled import counts and observed RUs, remain visible. Canceled partial results are not written as successful redirected output. Successful writes are not rolled back, and canceled in-flight writes may require reconciliation before retrying. Stopping watch with Ctrl+C is intentional and remains successful; enclosing pipelines, blocks, and scripts stop without running subsequent work. An interrupted stdin script also skips any separately supplied -c or -k command, even when watch handled the interruption successfully.

Interruption also applies while stdin is still being read and while a confirmation prompt is waiting. At a confirmation, n or Escape declines normally; Ctrl+C interrupts the operation. Stopping a watch expression stops its enclosing assignment or command before it changes a variable or performs subsequent work. Interrupt markers are not written to machine-readable or redirected stdout.

Scripted bulk writes require --yes; use --dry-run to preview first. Bulk operations are not transactional, and an exhausted observed RU budget returns exit code 6. Supply --journal on the original run and reuse that same journal to resume; without it, reconcile completed writes before retrying. See bulk operations for recovery and partial-success semantics.

Environment Variables

Variable Description
COSMOSDB_SHELL_TOKEN Pre-obtained Entra ID access token (JWT) for single-shot auth
COSMOSDB_SHELL_ACCOUNT_KEY Account key for authentication
COSMOSDB_SHELL_CSVSEP CSV column separator
COSMOSDB_SHELL_CSV_SCALAR_COLUMN Header for non-object CSV export rows (empty by default)
COSMOSDB_SHELL_FORMAT Default output format (user, json, table, csv) used when --output is not supplied. Supplies a format only — it does not enable machine mode
OTEL_EXPORTER_OTLP_ENDPOINT Default OTLP endpoint used by --otel when no endpoint is supplied

Examples:

# Run a query and exit
cosmosdbshell -c "connect $CONN; cd mydb/mycont; ls -m 5"

# Start connected to a specific account
cosmosdbshell --connect "AccountEndpoint=...;AccountKey=..."

# Start directly in a specific container without constructing a `-k` command
cosmosdbshell --connect "AccountEndpoint=...;AccountKey=..." --database mydb --container mycontainer

# Start connected with explicit ARM account context
cosmosdbshell --connect https://myaccount.documents.azure.com:443/ --connect-subscription <subscription-id> --connect-resource-group <resource-group>

# Start with MCP server enabled on the default port (6128)
cosmosdbshell --mcp

# Start with MCP server enabled on a custom port
cosmosdbshell --mcp 5050

# The same server also accepts legacy clients at http://127.0.0.1:5050/sse

# Capture a diagnostic log to the default location in the config directory
cosmosdbshell --diagnostics

# Capture a diagnostic log to a custom file
cosmosdbshell --diagnostics mylog.log

# Enable distributed tracing (emits a sampled traceparent on Cosmos requests)
cosmosdbshell --otel

# Enable distributed tracing and export spans to an OTLP collector
cosmosdbshell --otel http://localhost:4317