Your Agent Script Works Over SSH. Under Cron It Quietly Does Nothing.

You SSH into the Pi, run ./run-publish.sh, and it works. The agent drafts the post, gh opens the PR, the Discord webhook fires. You add it to crontab for 3 a.m. and go to bed. In the morning there is no PR, no Discord message, and no error anywhere you can find. Running it by hand again works fine.

The script didn’t change. The environment did. When you run something over SSH, it inherits everything your login shell built up: the PATH that nvm, pyenv, and ~/.local/bin added, the API keys exported from .bashrc, your SSH agent, your locale, and the directory you happened to be standing in. Cron gives the job almost none of that.

This post covers how to see exactly what cron gives you, reproduce it by hand, and write jobs that bring their own environment so they behave the same at 3 a.m. as they do in your terminal.

What cron actually hands your script

On Debian and Raspberry Pi OS, a cron job typically starts with something close to this:

  • PATH=/usr/bin:/bin. No /usr/local/bin, no ~/.local/bin, no nvm or pyenv shims. node, npx, openclaw, gh, and pip-installed tools often aren’t found.
  • SHELL=/bin/sh, which is dash on Debian. Bash syntax in the crontab line itself ([[ ]], source, brace expansion) breaks.
  • HOME and LOGNAME from /etc/passwd, and the working directory is HOME. Relative paths like ./state/last-run.json point somewhere else.
  • No .bashrc, .profile, or .env sourced. OPENAI_API_KEY, DISCORD_WEBHOOK_URL, and friends are empty.
  • No SSH_AUTH_SOCK. git push over SSH has no agent to ask for a key.
  • Usually no LANG or TZ, so you get the C locale and the system timezone.
  • Output goes to local mail via MAILTO. On most Pis nothing is configured to deliver it, so errors vanish.

Any one of these can make a job fail. A few of them, like an empty webhook URL with curl that doesn’t use -f, make it “succeed” while doing nothing.

Step 1: Capture the real cron environment

Don’t guess. Add a temporary line to your crontab with crontab -e:

* * * * * env > /tmp/cron-env.txt

Wait a minute, confirm the file exists, then remove that line. Now capture your interactive environment and compare:

env | sort > /tmp/shell-env.txt
sort /tmp/cron-env.txt > /tmp/cron-env.sorted
diff /tmp/cron-env.sorted /tmp/shell-env.txt

Your interactive environment almost certainly contains secrets. Read the diff on the box, don’t paste it anywhere, and delete /tmp/shell-env.txt when you’re done.

To reproduce the cron environment by hand, start from an empty environment with env -i and load only the captured variables:

mapfile -t CRONVARS < /tmp/cron-env.txt
cd ~ && env -i "${CRONVARS[@]}" /bin/sh -c '/home/pi/agent/bin/run-publish.sh'

mapfile keeps each NAME=value line intact, even if a value contains spaces. If the script fails here, you’ve reproduced the cron failure in your terminal, where you can actually see it. Iterate in this mode until it passes.

Step 2: A wrapper that brings its own environment

The durable fix is to stop depending on any inherited environment. Every scheduled job goes through a wrapper that sets up everything explicitly.

First, put secrets in a dedicated env file, readable only by you:

mkdir -p ~/.config/agent
nano ~/.config/agent/agent.env
chmod 600 ~/.config/agent/agent.env

Use plain KEY=value lines with no export, so the same file works for systemd later:

OPENAI_API_KEY=sk-...
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
GH_TOKEN=...

Find the absolute paths of your tools from an interactive shell, since nvm and pyenv put them in versioned directories:

command -v node gh openclaw

Then the wrapper:

#!/usr/bin/env bash
# /home/pi/agent/bin/run-publish.sh
set -euo pipefail

AGENT_DIR="/home/pi/agent"
LOG="$AGENT_DIR/logs/publish.log"
ENV_FILE="/home/pi/.config/agent/agent.env"

export PATH="/home/pi/.nvm/versions/node/v22.11.0/bin:/home/pi/.local/bin:/usr/local/bin:/usr/bin:/bin"
export LANG=C.UTF-8
export TZ=America/Chicago

cd "$AGENT_DIR"
mkdir -p "$AGENT_DIR/logs"
exec >> "$LOG" 2>&1

log() { printf '%s %s\n' "$(date -Is)" "$*"; }
trap 'log "FAILED at line $LINENO (exit $?)"' ERR

set -a
# shellcheck source=/dev/null
source "$ENV_FILE"
set +a

for bin in node gh openclaw; do
  command -v "$bin" >/dev/null || { log "missing binary: $bin"; exit 127; }
done

log "start run-publish"
node "$AGENT_DIR/publish.js"
log "done run-publish"

What each part is doing:

  • The bash shebang means bash features work regardless of what cron uses as its shell.
  • set -euo pipefail turns a failed command, an unset variable, or a failed stage of a pipe into a real failure.
  • cd to an absolute directory fixes every relative path in the script.
  • The explicit PATH replaces the one your login shell built. Update it when you upgrade Node.
  • set -a around source exports every variable in the env file, so child processes like node actually see them.
  • exec >> "$LOG" 2>&1 sends everything after it to a log you control, and the ERR trap records where it died.

The log never prints secret values. If you need to debug which variables are loaded, log their names or lengths, never their contents.

Step 3: Crontab hygiene

Even with a wrapper, set sane defaults at the top of the crontab:

SHELL=/bin/bash
PATH=/home/pi/.local/bin:/usr/local/bin:/usr/bin:/bin
MAILTO=""

0 3 * * * /home/pi/agent/bin/run-publish.sh >> /home/pi/agent/logs/cron.log 2>&1

The >> ... 2>&1 on the crontab line catches anything that happens before the wrapper’s own redirect, such as a typo in the script path or a permission error. MAILTO="" is fine once you’re logging properly; without a log, it just throws errors away.

Watch for %. In a crontab command, an unescaped % becomes a newline, and everything after it is sent to the command’s stdin. This line silently breaks:

0 2 * * * tar czf /home/pi/backups/agent-$(date +%F).tgz /home/pi/agent/state

Escape it as \%, or better, move the logic into a script:

0 2 * * * tar czf /home/pi/backups/agent-$(date +\%F).tgz /home/pi/agent/state

On timezones: cronie supports CRON_TZ= to schedule jobs in a specific zone, but support varies between cron implementations, so check man 5 crontab on your own box before relying on it. Set the system timezone with timedatectl set-timezone and set TZ inside the wrapper if your job’s own timestamps need a particular zone.

Step 4: The systemd timer equivalent

A user-level systemd timer gives you the journal, exit status tracking, and Persistent=true to catch up on runs missed while the box was off.

~/.config/systemd/user/agent-publish.service:

[Unit]
Description=Agent publish job

[Service]
Type=oneshot
WorkingDirectory=/home/pi/agent
EnvironmentFile=/home/pi/.config/agent/agent.env
Environment=PATH=/home/pi/.nvm/versions/node/v22.11.0/bin:/home/pi/.local/bin:/usr/local/bin:/usr/bin:/bin
Environment=LANG=C.UTF-8
ExecStart=/home/pi/agent/bin/run-publish.sh

~/.config/systemd/user/agent-publish.timer:

[Unit]
Description=Run agent publish nightly

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target

Enable it:

systemctl --user daemon-reload
systemctl --user enable --now agent-publish.timer
systemctl --user list-timers

The caveat: user services run inside your user’s systemd instance, which normally exists only while you’re logged in. Close your SSH session and the timer can stop firing. Enable lingering so your user manager starts at boot and stays up:

sudo loginctl enable-linger pi
loginctl show-user pi --property=Linger

The same applies to quick tests with systemd-run --user --on-calendar=.... Without linger, they disappear when you log out. Check results with journalctl --user -u agent-publish.service.

Step 5: Git over SSH without an agent

Interactively, git push works because your SSH agent or keychain holds an unlocked key. Under cron there’s no SSH_AUTH_SOCK, so the push fails, or hangs waiting for a passphrase nobody will type.

Use a dedicated deploy key without a passphrase, scoped to the one repo, and point git at it explicitly:

ssh-keygen -t ed25519 -N "" -f ~/.ssh/agent_deploy -C "pi agent deploy key"

Add the public key as a deploy key with write access on that repository. Then make sure the host key is already trusted, so the first unattended run doesn’t stop at a prompt:

ssh-keyscan github.com >> ~/.ssh/known_hosts

Either set the command in the wrapper:

export GIT_SSH_COMMAND="ssh -i /home/pi/.ssh/agent_deploy -o IdentitiesOnly=yes -o BatchMode=yes"

Or use a host alias in ~/.ssh/config:

Host github-agent
  HostName github.com
  User git
  IdentityFile /home/pi/.ssh/agent_deploy
  IdentitiesOnly yes
  BatchMode yes

and set the remote to git@github-agent:owner/repo.git. BatchMode=yes makes SSH fail immediately instead of waiting for input, which is what you want from a scheduled job.

Step 6: A preflight that fails loudly

The last piece makes missing configuration a recorded failure instead of a silent no-op. Run it at the top of the wrapper, right after sourcing the env file:

#!/usr/bin/env bash
# /home/pi/agent/bin/preflight.sh
set -uo pipefail

REQUIRED_BINS=(node gh openclaw git curl)
REQUIRED_VARS=(OPENAI_API_KEY DISCORD_WEBHOOK_URL GH_TOKEN)
problems=()

for b in "${REQUIRED_BINS[@]}"; do
  command -v "$b" >/dev/null || problems+=("missing binary: $b")
done

for v in "${REQUIRED_VARS[@]}"; do
  [[ -n "${!v:-}" ]] || problems+=("empty env var: $v")
done

[[ -w "$PWD" ]] || problems+=("working dir not writable: $PWD")

if (( ${#problems[@]} )); then
  msg="preflight failed on $(hostname): ${problems[*]}"
  echo "$msg" >&2
  if [[ -n "${DISCORD_WEBHOOK_URL:-}" ]]; then
    curl -fsS -H 'Content-Type: application/json' \
      -d "{\"content\":\"$msg\"}" "$DISCORD_WEBHOOK_URL" >/dev/null || true
  fi
  exit 1
fi
echo "preflight ok"

In the wrapper:

"$AGENT_DIR/bin/preflight.sh"

Because the wrapper uses set -e, a failed preflight stops the job with a non-zero exit. Cron’s log, or systemctl --user status, shows a failure, and the Discord alert names variables, never their values. ${!v} reads the variable named in v, so the check reports empty env var: GH_TOKEN without echoing what the token is.

Make this a standing routine

The pattern is the same for every job: capture the environment once, then never depend on it again. Grab one of the free prompts and adapt it into a “review this cron job for PATH, env file, working directory, and SSH assumptions” routine before you schedule anything new. For ready-made wrappers, preflights, and the rest of the guardrails for scheduled agent jobs, the OpenClaw Agent Ops Toolkit collects them in one place. The Ultimate Bundle includes everything for $49.

More from the build log

Suggested

Want the full MarketMai stack?

Get the core MarketMai guides and operator playbooks in one premium bundle for $49.

View Bundle