Skip to main content
GuidesScripts and automations

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 has the detail.

The recipes use the darkgrade command from a global install and jq to read JSON. With npx, write npx darkgrade instead. They run in bash and zsh.

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). The timelapse script below shows where it goes:

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.

#!/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
# 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.
  • 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:

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 integration exposes a shell command as an action), a button on a stream deck, a webhook handler.

#!/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).

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.

#!/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 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 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.

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 apart.

#!/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 brackets the same way with 0.0, +1.0 and +2.0. A negative value cannot be passed from the CLI today (why).
  • The camera's own bracket is a 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.

#!/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 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:

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 first.

Check battery and card first

Stop a long job before it starts if the camera will not last.

#!/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 and 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.

#!/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 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 returns a small JPEG:

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.

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:

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:

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.

React to the camera

watch prints a line when a setting changes on the camera or a new file lands on the card.

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:

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

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:

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:

    until darkgrade cameras --json |
        jq -e 'any(.cameras[]; .state == "ready")' > /dev/null; do
      sleep 2
    done
  • Unstick a camera. recover 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:

    if ! darkgrade camera recover --json |
        jq -e '.recovered' > /dev/null; then
      echo "Switch the camera off and on, or replug it" >&2
    fi

Next

⌘I