Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Automation and Troubleshooting

The commands in the earlier chapters also work in scripts. This chapter shows how to run gog without a terminal, parse JSON with jq, handle exit codes, select accounts, schedule jobs with cron or systemd, and diagnose authentication failures.

You will build inbox-digest.sh, which lists unread threads from the last day in Markdown.

Outputs shown here were captured from gog v0.48.1 in a throwaway home (GOG_HOME=$(mktemp -d)) with no Google account signed in. Commands that need a signed-in account appear without output.

Authentication and Accounts defines the credentials and permissions used in this chapter.

An OAuth client is the client ID and secret, downloaded from the Google Cloud console as a JSON file, that identify gog to Google. An OAuth scope is a named permission, such as read-only Gmail access, that you approve when you authorize an account. A refresh token is the long-lived credential that gog stores for an account and exchanges for short-lived access tokens.

Running without a terminal

A scheduled job has no one to answer a prompt, so it must never wait for input. The root flag --no-input makes gog fail when it would otherwise prompt, and gog also fails on prompts whenever standard input is not a terminal (internal/cmd/root.go). Pass the flag explicitly to keep the same behavior when testing the job by hand.

These 3 habits keep unattended runs predictable:

  • Authorize interactively, run unattended. gog auth add opens a browser consent flow; in v0.48.1 it starts that flow even under --no-input and only gives up when the authorization times out. Run it once by hand, or install a refresh token non-interactively with gog auth import (see Authentication and Accounts).
  • Read data from standard output only. gog writes results to stdout and writes prompts, progress, warnings and diagnostics to stderr (docs/automation.md), so 2>>log keeps the data stream clean.
  • Set the safety flags explicitly. Read-only jobs should pass --readonly, and any job that touches Gmail should pass --gmail-no-send unless sending is its purpose. Safety Controls for Scripts and Agents explains both.

JSON output and jq

--json (or -j) prints 1 JSON document on stdout. --plain prints tab-separated text (docs/automation.md). Setting GOG_JSON=1 makes JSON the default for every command in that environment, and an explicit --plain still overrides it. See Output, Schemas and Dry Runs for format details.

List commands wrap their results in an envelope. For gog gmail search, the envelope holds a threads array, a nextPageToken, and 2 fields that gog adds to paged lists: count, the number of rows in this response, and has_more, which is true when nextPageToken is not empty. The total number of matches on the server is separate from these pagination fields.

Use these 2 flags to reshape the result.

  • --results-only drops the envelope and prints only the primary array.
  • --select keeps only the named fields, for example --results-only --select id.

When a command fails in JSON mode, gog still prints the human message on stderr, and it also prints an error object on stdout whose code equals the exit status and whose class names it:

$ gog --account you@example.com --json --no-input gmail search 'is:unread'
OAuth client credentials missing (OAuth client ID JSON).
Download from: https://console.cloud.google.com/apis/credentials (Create Credentials → OAuth client ID → Desktop app → Download JSON)
Then run: gog auth credentials <credentials.json> (expected at /tmp/tmp.CNJtqGbBZU/data/credentials.json)
{"error":{"class":"config","code":10,"message":"OAuth client credentials missing (OAuth client ID JSON).\nDownload from: https://console.cloud.google.com/apis/credentials (Create Credentials → OAuth client ID → Desktop app → Download JSON)\nThen run: gog auth credentials <credentials.json> (expected at /tmp/tmp.CNJtqGbBZU/data/credentials.json)"}}

A jq filter that expects .threads will therefore fail on an error object, so check the exit status before you parse.

Exit codes

gog maps failures to stable exit codes, defined in internal/cmd/exit_codes.go, and gog schema exposes the map for programs to read.

$ gog --json schema | jq -c '.automation.exit_codes'
{"auth_required":4,"cancelled":130,"config":10,"empty_results":3,"error":1,"not_found":5,"ok":0,"orphaned":11,"permission_denied":6,"rate_limited":7,"retryable":8,"usage":2}
CodeNameTypical cause in a mail or calendar job
0oksuccess
1erroranything gog does not classify, such as a local network failure
2usagea bad flag, or a refusal by a safety check
3empty_resultsno results, only when you pass --fail-empty
4auth_requiredno token for the account, or an expired or revoked token
5not_foundthe message, thread or event does not exist
6permission_deniedGoogle returned HTTP 403, for example because a scope is missing
7rate_limitedquota still exhausted after gog’s own retries
8retryablea server error or a timeout
10configno OAuth client configured on this machine
130cancelledinterrupted with Ctrl-C

Branch on the status and keep a generic fallback, since later releases may add codes:

if json="$(gog --no-input --json gmail search --max 20 -- 'is:unread newer_than:1d')"; then
  printf '%s\n' "$json" | jq '.count'
else
  rc=$?
  case "$rc" in
    4) printf 'token missing or expired; run gog auth add again\n' >&2 ;;
    7 | 8) printf 'temporary failure; the next run will retry\n' >&2 ;;
    10) printf 'gog has no OAuth client on this machine\n' >&2 ;;
    *) printf 'gog failed with exit code %s\n' "$rc" >&2 ;;
  esac
  exit "$rc"
fi

Choosing the account and the client

A script should not depend on whichever account happens to be the default. gog resolves the account from --account first, then from GOG_ACCOUNT, then from the stored default account (docs/quickstart.md). Setting GOG_ACCOUNT in the job’s environment therefore lets one script serve several accounts without changes.

An account alias is a short name that stands for an address, set with gog auth alias set. The OAuth client name, chosen with --client or GOG_CLIENT, selects which credentials file and which stored token gog uses, so the same account can have a read-only token under one client name and a broader one under another. The per-user config.json contains aliases, client mappings, and per-account send guards.

$ gog auth alias set me you@example.com
alias	me
email	you@example.com
$ gog auth alias set work you@example.org
alias	work
email	you@example.org
$ gog config no-send set you@example.org
No-send enabled for you@example.org
$ gog config set timezone America/Toronto
Set timezone = America/Toronto
$ cat "$(gog config path)"
{
  "default_timezone": "America/Toronto",
  "account_aliases": {
    "me": "you@example.com",
    "work": "you@example.org"
  },
  "no_send_accounts": {
    "you@example.org": true
  }
}

gog config keys lists the keys you can set with gog config set: timezone, keyring_backend, gmail_no_send, youtube_api_key and places_api_key. Mappings from accounts or domains to client names (account_clients, client_domains) are described in docs/auth-clients.md.

Project: inbox-digest.sh

The script prints unread threads from the last day as a Markdown list you can paste into a note or email to yourself. It searches with gog --json gmail search under --readonly, so even a mistake in the script cannot change the mailbox.

#!/usr/bin/env bash
set -euo pipefail

gog_bin="${GOG:-gog}"
query="${DIGEST_QUERY:-is:unread newer_than:1d}"
max="${DIGEST_MAX:-100}"

digest_filter='
  def md: gsub("(?<c>[\\\\`*_\\[\\]<>#])"; "\\\(.c)");
  def line:
    "- **\((.subject // "") | if . == "" then "(no subject)" else md end)**"
    + " from \((.from // "unknown sender") | md)"
    + (if .date then ", \(.date)" else "" end)
    + (if (.messageCount // 1) > 1 then " (\(.messageCount) messages)" else "" end);
  "## Unread threads (\(.threads | length))",
  "",
  (if (.threads | length) == 0 then "No unread threads." else (.threads[] | line) end),
  (if .has_more then "", "_More threads match; raise DIGEST_MAX to see them._" else empty end)
'

json="$("$gog_bin" --readonly --no-input --json gmail search --max "$max" -- "$query")"
printf '%s\n' "$json" | jq -r "$digest_filter"

The script handles query parsing, result limits, and failures as follows.

  • gmail search returns 10 threads unless told otherwise, so the script sets --max and prints a note when has_more reports that more threads match.
  • The query follows --, which ends flag parsing; everything after it is query text, even a term that starts with a dash.
  • The jq function md escapes characters that Markdown would interpret, such as * and [ in a subject line.
  • Most thread fields are omitted from the JSON when they are empty, so the filter supplies a default for each one.
  • GOG lets you point the script at another binary, such as a baked gog-agent-safe, and DIGEST_QUERY lets you reuse it for other searches.
  • If gog fails, the assignment to json fails, and set -e ends the script with gog’s own exit code. In a home without an OAuth client, for example, the script exits with 10.

Testing the filter without an account

Use this sample to test the jq filter without signing in. gog schema describes commands, flags, exit codes, and the safety state. The sample takes its result fields from the threadItem type in internal/cmd/gmail_thread_search_helpers.go for each thread and from addPagedAggregates in internal/cmd/paged_list_helpers.go for count and has_more.

The second thread has no subject, and the third contains only an ID. These entries test the filter’s defaults.

{
  "count": 3,
  "has_more": false,
  "nextPageToken": "",
  "threads": [
    {
      "id": "thread-a",
      "date": "2026-11-27 08:15",
      "internalDateIso": "2026-11-27T08:15:02-05:00",
      "from": "Friend <friend@example.com>",
      "subject": "Agenda for *Friday* [draft]",
      "labels": ["INBOX", "UNREAD"],
      "messageCount": 3
    },
    {
      "id": "thread-b",
      "date": "2026-11-26 19:40",
      "internalDateIso": "2026-11-26T19:40:11-05:00",
      "from": "friend@example.com",
      "labels": ["INBOX", "UNREAD"],
      "messageCount": 1
    },
    {
      "id": "thread-c"
    }
  ]
}

To run the whole script against the sample, point GOG at a stub that ignores its arguments and prints the file:

#!/usr/bin/env bash
cat "$FIXTURE"
$ GOG=./fake-gog FIXTURE=sample.json ./inbox-digest.sh
## Unread threads (3)

- **Agenda for \*Friday\* \[draft\]** from Friend \<friend@example.com\>, 2026-11-27 08:15 (3 messages)
- **(no subject)** from friend@example.com, 2026-11-26 19:40
- **(no subject)** from unknown sender

With {"count":0,"has_more":false,"nextPageToken":"","threads":[]} the script prints the heading ## Unread threads (0) followed by No unread threads., and with has_more set to true it appends the note about DIGEST_MAX. The script passes shellcheck without warnings.

Watching for new mail and calendar changes

gog’s polling guide, docs/polling.md, covers Drive changes and Docs comments only; drive changes poll and docs comments poll keep their cursor in a state file and can run a hook per event. For Gmail and Calendar you choose between 3 approaches:

ApproachCommandWhat it needs
Repeat a search on a schedulegog gmail search 'is:unread newer_than:1h'nothing beyond a token
Read the change history since a cursorgog gmail history --since <historyId>a stored history ID
Receive push notificationsgog gmail watch start, then gog gmail watch pull or gog gmail watch servea Google Cloud Pub/Sub topic and subscription

A Gmail history ID is a mailbox-wide counter that increases with every change. gog gmail history --since lists the IDs of messages added after the given history ID, and its JSON output carries the current historyId, which becomes the cursor for the next run.

To obtain a first cursor, read it from any message: the message object in gog gmail get <messageId> --json is Gmail’s message resource, which includes historyId. A cursor that Gmail no longer accepts has to be reset the same way; docs/watch.md recommends falling back to a normal message listing in that case.

#!/usr/bin/env bash
set -euo pipefail

state="${XDG_STATE_HOME:-$HOME/.local/state}/gog-new-mail/history-id"
since="$(cat "$state")"

json="$(gog --readonly --no-input --json gmail history --since "$since" --all)"
printf '%s\n' "$json" | jq -r '.messages[]?'
printf '%s\n' "$json" | jq -r '.historyId' >"$state.tmp"
mv "$state.tmp" "$state"

The script prints 1 message ID per line and advances the cursor only after a successful read. The push approach, described in the same Gmail watch guide, suits a long-running service more than a scheduled job, because it needs a Pub/Sub subscription and credentials that can consume it.

For Calendar, gog calendar changed lists the most recently changed events, including deletions. Its --since flag takes an RFC 3339 timestamp, a date or a Go duration such as 24h, and defaults to 30 days, as its generated page docs/commands/gog-calendar-changed.md shows. A daily job can run gog --readonly --json calendar changed --since 24h.

Rate limits and retries

gog retries rate-limited requests automatically. Per docs/automation.md, a request that receives HTTP 429, or HTTP 403 with the reason rateLimitExceeded or userRateLimitExceeded, is retried up to 6 times with exponential backoff and jitter, which spans just under 94.5 seconds in total.

A Retry-After header is honored for delays up to 60 seconds per retry. If the quota is still exhausted afterward, the command exits with 7 (rate_limited); server errors and timeouts exit with 8 (retryable).

A scheduled job therefore needs no retry loop of its own. Let the run fail with 7 or 8 and rely on the next scheduled run, which avoids piling extra requests onto a quota that is already exhausted.

Running from cron or a systemd timer

A scheduler starts the job with a minimal environment: no login shell, often a short PATH, and no desktop session for the system keyring. Set the job’s environment explicitly. The keyring is where gog stores tokens; on a machine without a desktop session, use the encrypted file backend and supply its password through the environment, as docs/install.md describes for headless agents.

Keep the variables in a file that only you can read (mode 0600), for example ~/.config/inbox-digest/env:

GOG=/usr/local/bin/gog
GOG_ACCOUNT=you@example.com
GOG_KEYRING_BACKEND=file
GOG_KEYRING_PASSWORD=replace-with-your-keyring-password

The digest script also calls jq, so add a PATH= line to the file if jq lives outside the scheduler’s default path.

A systemd user service and timer then run the digest on weekday mornings. Save the service as ~/.config/systemd/user/inbox-digest.service:

[Unit]
Description=Unread mail digest

[Service]
Type=oneshot
EnvironmentFile=%h/.config/inbox-digest/env
ExecStart=/bin/sh -c '%h/bin/inbox-digest.sh > %h/inbox-digest.md'

and the timer as ~/.config/systemd/user/inbox-digest.timer:

[Unit]
Description=Run the unread mail digest on weekday mornings

[Timer]
OnCalendar=Mon..Fri 07:00
Persistent=true

[Install]
WantedBy=timers.target

Activate the timer, then run the service once by hand through systemd, which tests the same environment the timer will use:

systemctl --user daemon-reload
systemctl --user enable --now inbox-digest.timer
systemctl --user start inbox-digest.service
journalctl --user -u inbox-digest.service -n 20

With cron, the same job is one line in crontab -e. The set -a makes the shell export every variable it reads from the file:

0 7 * * 1-5 set -a; . "$HOME/.config/inbox-digest/env"; "$HOME/bin/inbox-digest.sh" > "$HOME/inbox-digest.md" 2>> "$HOME/inbox-digest.log"

Test any change by running the job through the scheduler itself. A command that works in your terminal only proves that your terminal has the right environment.

Diagnosing failures with gog auth doctor

gog auth doctor checks the local pieces that authentication depends on: the config file, the keyring backend and its password, and the stored tokens. With --check it also exchanges each refresh token for an access token, which proves that Google still accepts it. In a fresh home it reports a warning:

$ gog auth doctor
ok	config.path	/tmp/tmp.CNJtqGbBZU/config/config.json (optional; not created)
ok	keyring.backend	auto (source: default)
ok	keyring.dir	/tmp/tmp.CNJtqGbBZU/data/keyring
ok	keyring.open	opened
warn	tokens	no OAuth tokens stored
hint	tokens	run `gog auth add <email>`
status	warn

gog auth doctor exits with code 0 whenever it produces a report, including one with errors. In scripts, check the overall status field. The following preflight continues only when the status is ok:

doctor_json="$(gog --no-input --json auth doctor --check)"
if ! printf '%s\n' "$doctor_json" | jq -e '.status == "ok"' >/dev/null; then
  printf 'gog auth doctor did not report ok; not running the job\n' >&2
  exit 4
fi

gog auth doctor validates OAuth refresh tokens only. To test a service account, Application Default Credentials, or a direct access token, make a short read request.

Common failures and fixes

SymptomExit codeCauseFix
OAuth client credentials missing (OAuth client ID JSON).10no OAuth client on this machine, or a different GOG_HOMEgog auth credentials <file.json>; check that the job sees the same GOG_HOME
No auth for gmail you@example.com.4no stored token for this account and clientgog auth add you@example.com --services ..., with the same --client the job uses
a refresh fails with invalid_grant4the token expired or was revokedreauthorize the same account and client, keeping its services and scope modes
a call fails with HTTP 403 after you started using a new service6the token lacks that service’s scopereauthorize with the complete service list
no TTY available for keyring file backend password prompt1file keyring without GOG_KEYRING_PASSWORD in the job’s environmentadd the variable to the environment file the scheduler loads
keyring connection timed out ... (D-Bus SecretService may be unresponsive)1the system keyring is unreachableswitch to the file backend, or raise GOG_KEYRING_OPEN_TIMEOUT

Missing credentials

gog needs the OAuth client file before it can use any token. The message names the path where it looked, which reveals a GOG_HOME or user mismatch at a glance.

Missing token

Captured with a valid client but no token:

$ gog --account you@example.com --no-input gmail search 'is:unread'
No auth for gmail you@example.com.

OAuth (browser flow):
  gog auth add you@example.com --services gmail

Workspace service account (domain-wide delegation):
  gog auth service-account set you@example.com --key <service-account.json>
$ echo $?
4

The suggested gog auth add command omits the client name. If the job runs with --client reader, run gog --client reader auth add ... instead, or the new token lands in the default bucket.

Expired or revoked token

When Google rejects a refresh with invalid_grant, ordinary commands exit with 4 and auth doctor --check reports the failed refresh. Before you reauthorize, run gog auth list --json and note the account’s client, services and scope modes, because a bare gog auth add --force-consent requests the default services (docs/quickstart.md). Tokens that expire every 7 days usually indicate that the OAuth app is still in Testing mode on Google’s side; the quickstart describes how to publish it.

Missing scope after adding a service

A token covers only the services it was granted. If a job that used to read mail now also lists events, but the token was granted for Gmail only, Google answers the calendar call with HTTP 403 and gog exits with 6 (permission_denied). Reauthorize with every service the account needs, for example gog auth add you@example.com --services gmail,calendar --force-consent, keeping --readonly or the client name if the original grant used them.

Locked or unreachable keyring

On a headless machine the file keyring cannot ask for its password, and the doctor says so directly:

$ GOG_KEYRING_BACKEND=file gog --no-input auth doctor
ok	config.path	/tmp/tmp.uc7dAWGAOK/config/config.json (optional; not created)
ok	keyring.backend	file (source: env)
ok	keyring.dir	/tmp/tmp.uc7dAWGAOK/data/keyring
error	keyring.password	file keyring selected but GOG_KEYRING_PASSWORD is not set in a non-interactive process
hint	keyring.password	set GOG_KEYRING_PASSWORD or switch to a system keyring
ok	keyring.open	opened
warn	tokens	no OAuth tokens stored
hint	tokens	run `gog auth add <email>`
status	error

A real command in the same situation fails with ... no TTY available for keyring file backend password prompt; set GOG_KEYRING_PASSWORD and exit code 1. On a desktop whose Secret Service does not respond, storing a secret fails instead with:

store OAuth client secret: store secret: set secret: keyring connection timed out after 10s while storing keyring item (D-Bus SecretService may be unresponsive); set GOG_KEYRING_OPEN_TIMEOUT to allow more time, or set GOG_KEYRING_BACKEND=file and GOG_KEYRING_PASSWORD=<password> to use encrypted file storage instead

docs/paths.md adds a related setting for containers and other headless Linux hosts: DBUS_SESSION_BUS_ADDRESS=disabled: stops the keyring library from trying to start a session bus, and GOG_KEYRING_BACKEND=auto then selects the file backend.