--- title: "Scripts and automations" description: "Copy-and-adapt darkgrade recipes: a cron timelapse, focus stacking, HDR brackets, a photo on a trigger, card backups and bash + jq patterns." url: https://darkgrade.com/docs/cli/scripting last_updated: 2026-12-04 docs_index: https://darkgrade.com/docs/llms.txt --- # Scripts and automations > Copy-and-adapt darkgrade recipes: a cron timelapse, focus stacking, HDR brackets, a photo on a trigger, card backups and bash + jq patterns. > ## Documentation Index > Fetch the complete documentation index at: https://darkgrade.com/docs/llms.txt > Use this file to discover all available pages before exploring further. Put your camera in a shell script, a cron job or a home automation with the Darkgrade CLI. Every recipe here is built from the same three facts: a command prints JSON with `--json`, exits non-zero when it fails, and opens and closes the camera by itself. [Output, JSON and exit codes](https://darkgrade.com/docs/cli/output.md) has the detail. The recipes use the `darkgrade` command from a [global install](https://darkgrade.com/docs/cli/install.md#run-or-install) and [`jq`](https://jqlang.org) to read JSON. With `npx`, write `npx darkgrade` instead. They run in bash and zsh. > [!NOTE] > > On a Mac, the system's camera service takes the camera back between commands. Every recipe here needs this line before each `darkgrade camera` line on a Mac ([why](https://darkgrade.com/docs/cli/install.md#if-a-ready-camera-will-not-open)). The timelapse script below shows where it goes: > > ```bash > killall -9 ptpcamerad PTPCamera mscamerad 2> /dev/null || true > ``` ## A timelapse from cron The computer is the intervalometer: cron takes one frame a minute, copied to this computer under the camera's own file name, with a log of every frame. ```bash #!/bin/bash # ~/bin/timelapse-frame.sh (make it executable: chmod +x) set -euo pipefail mkdir -p "$HOME/timelapse" cd "$HOME/timelapse" exec 2>> errors.log # macOS only: free the camera from the system's camera service killall -9 ptpcamerad PTPCamera mscamerad 2> /dev/null || true darkgrade camera take-photo --destination computer --no-autofocus --json \ >> frames.jsonl ``` ```bash # crontab -e PATH=/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin * * * * * $HOME/bin/timelapse-frame.sh ``` - Each photo lands in `~/timelapse` under the camera's own name, and its result is one line of `frames.jsonl`. Failures go to `errors.log`. - `--no-autofocus` releases without waiting for focus, so a frame is never skipped because the camera hunted. Focus once by hand before you start. - `--destination computer` also keeps each photo on the card. `computerOnly` sends it to the computer without saving it to the card. - Not every camera can release without autofocus or skip the card. `darkgrade camera get-capabilities --json | jq '.operations.takePhoto.options'` shows what yours supports. See [Take a photo](https://darkgrade.com/docs/functionality/photos.md#take-a-photo). - Cron runs with a short `PATH`. It must include the folders that `command -v darkgrade` and `command -v node` print. - Between frames nothing has the camera open, so its own power saving applies. For a long job, set the camera's auto power off to its longest time, or off, in the camera's menu, and run it from mains power. For an interval under a minute, loop instead: ```bash while :; do darkgrade camera take-photo --destination computer --no-autofocus --json \ >> frames.jsonl || echo "missed a frame at $(date)" >&2 sleep 10 done ``` Each command opens and closes the camera, which takes a moment, so leave a few seconds between frames. ## A photo when something happens Any tool that can run a command can take a photo: a doorbell or motion sensor in a home-automation hub such as Home Assistant (its [`shell_command`](https://www.home-assistant.io/integrations/shell_command/) integration exposes a shell command as an action), a button on a stream deck, a webhook handler. ```bash #!/bin/sh # on-doorbell.sh exec darkgrade camera take-photo --destination computer \ --output "/srv/doorbell/$(date +%s).jpg" --quiet ``` `--output` writes the path you give it and nothing else; the format is whatever the camera shoots. Set the camera to JPEG before saving as `.jpg` ([Photo format](https://darkgrade.com/docs/functionality/photos.md#photo-format)). The command runs where the tool runs it, so `darkgrade` and Node.js must be installed there and the camera plugged into that machine. On Home Assistant OS, Home Assistant says a shell command runs inside its own container and is stopped after 60 seconds. ## Focus stacking (a focus bracket) Take a run of photos with focus stepped a little farther each time, to merge in a stacking program. Focus on the nearest part of the subject first, by hand or with [`autofocus`](https://darkgrade.com/docs/functionality/focus.md#autofocus). ```bash #!/bin/bash set -euo pipefail frames=20 for _ in $(seq "$frames"); do darkgrade camera take-photo --no-autofocus --json >> stack.jsonl step=$(darkgrade camera nudge-focus far small --json) if [ "$(jq '.atLimit' <<<"$step")" = true ]; then break; fi done ``` - [`nudge-focus`](https://darkgrade.com/docs/functionality/focus.md#nudge-manual-focus) moves focus one `small`, `medium` or `large` step `near` or `far`. How far a step moves depends on the lens, so try a few frames and pick the size and the count. - `atLimit` is true when the lens reached the end of its travel, and the loop stops there. A Canon never reports the end, so on a Canon the frame count ends the loop. - **Sony** steps focus only with the [focus mode](https://darkgrade.com/docs/functionality/focus.md#focus-mode) at `MF` or `DMF`: run `darkgrade camera set-focus-mode MF` first. - **Nikon** steps focus only in an autofocus mode such as `AF-S`, not `MF`. - **Canon** steps focus in live view, which the command turns on itself. - `--no-autofocus` keeps the photo from refocusing. Not every camera can release without autofocus: see the [timelapse notes](#a-timelapse-from-cron). ## Exposure bracketing for HDR Take the same frame at several shutter speeds, to merge into one HDR picture. In Manual mode with a fixed ISO, only the exposure time changes. These three are two [stops](https://darkgrade.com/docs/overview/glossary.md#stop) apart. ```bash #!/bin/bash set -euo pipefail darkgrade camera set-exposure-mode Manual for speed in 1/1000 1/250 1/60; do darkgrade camera set-shutter-speed "$speed" darkgrade camera take-photo --no-autofocus --json >> bracket.jsonl done ``` - Each speed must be one your camera offers right now. List them with `darkgrade camera get-capabilities --json | jq '.controls.shutterSpeed.allowedValues'`. - Set a fixed ISO first, such as `darkgrade camera set-iso 'ISO 100'`. With ISO on `Auto` the camera makes up the difference and the frames come out alike. - Use a tripod and focus once before you start, so the frames line up. - In a mode where the camera sets the exposure, [`set-exposure-compensation`](https://darkgrade.com/docs/functionality/exposure.md#exposure-compensation) brackets the same way with `0.0`, `+1.0` and `+2.0`. A negative value cannot be passed from the CLI today ([why](https://darkgrade.com/docs/cli.md#limits-to-know)). - The camera's own bracket is a [drive mode](https://darkgrade.com/docs/functionality/photos.md#drive-mode), such as `Single bracket 1.0 EV 3 frames`, where the camera offers one. This recipe does not use it: it changes the shutter speed itself, so each frame is one `take-photo`. ## Set up a shoot in one go Put the camera in a known state before you start. ```bash #!/bin/sh set -e darkgrade camera set-clock darkgrade camera set-exposure-mode Manual darkgrade camera set-shutter-speed 1/250 darkgrade camera set-aperture f/4 darkgrade camera set-iso 'ISO 400' darkgrade camera set-white-balance Daylight ``` `set -e` stops at the first setting the camera refuses, and the error says why. [`set-clock`](https://darkgrade.com/docs/functionality/power.md#set-the-clock) sets the camera's date and time to now, so file dates match the computer's. A value must be one the camera offers right now. List them for any setting: ```bash darkgrade camera get-capabilities --json | jq -r '.controls.whiteBalance.allowedValues[]' ``` Some settings depend on others: aperture cannot be set in a mode where the camera chooses it, for example. Set the [exposure mode](https://darkgrade.com/docs/functionality/exposure.md#exposure-mode) first. ## Check battery and card first Stop a long job before it starts if the camera will not last. ```bash #!/bin/bash set -euo pipefail percent=$(darkgrade camera get-battery --json | jq '.percent // empty | floor') if [ -n "$percent" ] && [ "$percent" -lt 20 ]; then echo "Battery at ${percent}%" >&2; exit 1 fi free=$(darkgrade camera get-card-status --json | jq '[.[] | select(.state == "ready") | .freeBytes // 0] | add // 0') if [ "$free" -lt 1000000000 ]; then echo "Less than 1 GB free on the card" >&2; exit 1 fi ``` A camera leaves out what it does not report (Canon reports a coarse `level` rather than `percent`), so every optional field needs a fallback. [Battery](https://darkgrade.com/docs/functionality/power.md#battery) and [Card space](https://darkgrade.com/docs/functionality/media.md#card-space) list the fields. ## Back up the card Copy every photo and clip you do not have yet into a folder, under its name on the card. ```bash #!/bin/bash set -euo pipefail dest="$HOME/Pictures/card-backup" mkdir -p "$dest" darkgrade camera list-media --json | jq -r '.[] | [.id, .name] | @tsv' | while IFS=$'\t' read -r id name; do [ -e "$dest/$name" ] && continue darkgrade camera download-media "$id" --output "$dest/$name.part" \ --quiet --json < /dev/null > /dev/null mv "$dest/$name.part" "$dest/$name" done ``` - [`list-media`](https://darkgrade.com/docs/functionality/media.md#list-photos-and-clips) lists files newest first. An `id` stays the same across reconnects while the file is on the card, so the script can run again and pick up where it stopped. - Writing to `.part` and renaming means an interrupted download is never mistaken for a finished file. - Add `select(.kind == "photo")` to the `jq` filter to copy photos only. For a quick look without the full file, [`get-media-preview`](https://darkgrade.com/docs/functionality/media.md#preview-a-file) returns a small JPEG: ```bash darkgrade camera get-media-preview "$id" --size preview --output preview.jpg ``` ## Record a clip and fetch it `start-recording` holds until `--duration` passes, stops, and prints the finished clip. ```bash clip=$(darkgrade camera start-recording --duration 30s --json) id=$(jq -r '.clip.mediaId' <<<"$clip") name=$(jq -r '.clip.name' <<<"$clip") darkgrade camera download-media "$id" --output "$name" ``` To stop on your own signal, run it in the background and send `SIGTERM`. The command stops the recording, waits for the clip and prints it before it exits: ```bash darkgrade camera start-recording --json > clip.json & recorder=$! # … do the take … kill -TERM "$recorder"; wait "$recorder" ``` Use the global install here, so the signal reaches `darkgrade` itself and not `npx`. ## See what the camera sees Save the current live-view picture as a JPEG, for a status page or a framing check from another room: ```bash darkgrade camera get-live-view-frame --output /srv/www/camera.jpg \ --quiet --json > /dev/null ``` The result also carries the camera's focus frames; see [Read a live-view frame](https://darkgrade.com/docs/functionality/live-view.md#read-a-live-view-frame). ## React to the camera [`watch`](https://darkgrade.com/docs/cli/output.md#watch-for-events) prints a line when a setting changes on the camera or a new file lands on the card. ```bash darkgrade camera watch --json | jq --unbuffered -r 'select(.event == "mediaAdded") | .at' | while read -r at; do echo "New file on the card at $at" done ``` While `watch` runs it has the camera open. To act on the new file, watch for a fixed time and then read the card: ```bash darkgrade camera watch --duration 5m --json > events.jsonl if grep -q mediaAdded events.jsonl; then darkgrade camera list-media --json | jq '.[0]' # the newest file fi ``` To copy each photo to a folder the moment it is taken, for Lightroom's Auto Import or Capture One's Hot Folder, keep the camera open in one program instead: Slate's [save each photo to a folder as you shoot](https://darkgrade.com/docs/slate/guides/events.md#save-each-photo-to-a-folder-as-you-shoot-for-lightroom-auto-import-or-capture-one) recipe does that. ## Several cameras Name the camera for one command with `--camera`, or for a whole script with `DARKGRADE_CAMERA`. This takes a photo on every ready camera, one after another: ```bash for id in $(darkgrade cameras --json | jq -r '.cameras[] | select(.state == "ready") | .usbId'); do darkgrade camera take-photo --camera "$id" --json done ``` The id names a model, so this works when the cameras are different models. ## Handle failures A failed command exits 1 and explains itself on standard error. Keep the two streams apart so a failure is never parsed as a result: ```bash if ! result=$(darkgrade camera take-photo --json 2> error.log); then echo "take-photo failed: $(cat error.log)" >&2 exit 1 fi ``` - **Retry reads, not writes.** `get-*`, `list-media` and `download-media` change nothing, so retry them freely. A command that acts (`take-photo`, `set-*`, `start-recording`) is sent once and never resent; if its result could not be confirmed, check the camera's state before sending it again. - **Wait for a camera.** `darkgrade cameras` exits 0 even with nothing attached. Test the JSON: ```bash until darkgrade cameras --json | jq -e 'any(.cameras[]; .state == "ready")' > /dev/null; do sleep 2 done ``` - **Unstick a camera.** [`recover`](https://darkgrade.com/docs/functionality/connection.md#recover-a-stuck-camera) tries a fresh session, then a device reset, then a USB port reset. It exits 0 whether or not the camera came back, so test the result: ```bash if ! darkgrade camera recover --json | jq -e '.recovered' > /dev/null; then echo "Switch the camera off and on, or replug it" >&2 fi ``` ## Next > [card] [Command reference](https://darkgrade.com/docs/cli/commands.md) > > Every command with its inputs and flags. > [card] [Functionality](https://darkgrade.com/docs/functionality/connection.md) > > What each operation does and returns, with its command under the CLI tab.