# Use div in scripts and CI

> Run div unattended, branch on its exit codes, read its JSON output, and stop runs from a script.

This guide shows how to call `div` from a shell script, a CI job or an agent. For the full rules on output and exit codes, see [Exit codes and errors](https://docs.divergentlabs.xyz/compute/cli/exit-codes.md).

## Authenticate without a browser

On a machine where nobody can run `div login`, set an API key in the environment. Create the key in the dashboard under **Settings**.

```bash
export DIVERGENT_API_KEY=dv_live_...
div whoami
```

See [Configuration](https://docs.divergentlabs.xyz/compute/cli/configuration.md) for the other settings you can pass this way.

## Keep the run's output separate from div's

`div` writes the run's output to stdout and its own messages to stderr. Redirect stdout to capture only what your program printed:

```bash
div run --gpu h100 eval.py > eval.log
div logs run-7 -f | grep loss
```

## Branch on the exit code

`div run` exits with the run's exit code. It exits `1` when the API rejects the request and `2` when the command is invalid.

```bash
if ! div run --gpu h100 train.py::run --max-spend 20; then
  echo "training failed with exit code $?" >&2
fi
```

## Check a metric, not only the exit code

A run that exits `0` did not crash, but it may still miss your target. Write the metric to the run's result file and add a `--check`. See [Report a run's metrics and check them](https://docs.divergentlabs.xyz/compute/guides/results.md).

```bash
div run --json eval.py --check 'metrics.accuracy>=0.8' > run.json
jq -e 'all(.checks[]; .verdict == "passed")' run.json > /dev/null || echo "check failed" >&2
div result "$(jq -r .name run.json)" metrics.accuracy
```

## Start a run without waiting

`--detach` prints the run's name to stdout and exits once the run has started:

```bash
name=$(div run --detach --gpu h200 --gpus 8 finetune.py::lora --max-spend 400)
div logs "$name" -f
```

Pressing Ctrl-C during an attached `div run` also detaches. The run keeps going until it finishes or reaches its spend limit.

## Read structured output

Add `--json` to `div run`, `div logs`, `div runs`, `div stop`, `div catalog`, `div whoami` and `div limits`. The output includes every field the API returns, including fields added after your version of `div`.

```bash
div runs --status active --json | jq -r '.[].name'
```

## Stop everything that is running

`div runs` prints one run per line with the name first and no header. `div stop` exits `0` even if the run has already finished.

```bash
div runs --status active | cut -d' ' -f1 | xargs -n1 div stop
```
