Skip to content

Latest commit

 

History

History
366 lines (268 loc) · 15.9 KB

File metadata and controls

366 lines (268 loc) · 15.9 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.

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 shell location:

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

Pipes and JSON Flow

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

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. History files written by older versions of the shell continue to load unchanged. 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.

Commands are stored in full so they can be executed again, including connection strings containing account keys. Treat the cmd_history file in the shell configuration directory as sensitive: protect it with your user account's file permissions and do not share it. 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. Use Entra ID to avoid storing account keys, or --clear-history to clear the saved history. MCP tool invocations are echoed as command lines and recorded in the same history.

Keyboard Shortcuts

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)

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 standard informational output (banners, connection logs). 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 (Model Context Protocol) server 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 early parser/connection failures as a structured { "status": "error", "error": ... } object on STDERR. 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.

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.

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

# 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