Skip to content

Variables

Gubarz edited this page May 19, 2026 · 1 revision

Variables

Variables make cheat commands interactive. CheatMD detects $name references in your command template and prompts for each one before execution. There are three ways to define a variable.

Prompt-only

var name

Asks the user to type a value. No options, no default.

Add a header label:

var name --- --header "Enter hostname"

From shell output (=)

var name = <shell command>

The shell command runs through your configured shell. Its output drives the picker UI:

Output Behavior
0 lines (empty) Falls back to a manual text prompt
1 line Pre-filled in the input; confirm with Enter or edit
2+ lines Filterable selection list

Examples:

var container = docker ps --format "{{.Names}}"
var branch    = git branch --format='%(refname:short)'
var port      = printf '%s\n' 22 80 443 8080

Editable defaults

echo "default" produces one line, which pre-fills the input:

var timeout = echo "10" --- --header "Timeout (seconds)"

The user can accept or overwrite before pressing Enter.

Literal (:=)

var name := <value>

No shell is run. The value is used directly, with $other_var substitution for variables resolved earlier in the same block:

var user := admin
var url  := https://$host/api/v1

Literal vars are typically used inside Conditionals to branch on a previous choice:

if $env == prod
  var url := https://api.example.com
fi

Variable syntax in commands

The var_syntax config setting controls which forms CheatMD recognizes as variable references in command text:

Setting Recognizes Example
dollar (default) $name ssh $user@$host
angle <name> ssh <user>@<host>
both both forms ssh $user@<host>

The companion setting allow_undeclared_vars: true makes CheatMD prompt for any referenced variable that has no <!-- cheat --> declaration, instead of silently skipping it.

With var_syntax: both and allow_undeclared_vars: true, this cheat works with no metadata block:

## SSH

```sh title:"SSH to a host"
ssh $user@<host> -p $port
```

DSL always uses $name

Inside <!-- cheat --> blocks, the DSL always uses $name syntax regardless of var_syntax. This keeps your metadata portable:

<!-- cheat
var user
var url := https://$host/api     -- always $host, never <host>
-->

Resolution order

Variables are resolved in the order they appear in the <!-- cheat --> block. A later variable's shell command can reference earlier resolved values:

var context   = kubectl config get-contexts -o name
var namespace = kubectl --context $context get ns -o name

$context is resolved first, then its value is substituted into the $namespace shell command.

Pre-filling from environment

If a variable name matches an environment variable (e.g., $USER, $HOME), the environment value is used as the pre-fill. The user can still override it.

See also

Clone this wiki locally