03 / ACCOUNTS, SERVICES AND JOBS · LESSON 12

Preserve scheduled-job outcomes

Capture stdout, stderr and exit status separately, publishing a report only after a successful job.

16 min · learn at your pace

Three outcomes travel together

A scheduled command produces standard output, standard error and an exit status. They answer different questions. Standard output may be a report; standard error carries diagnostics; the exit status says whether the command completed according to its contract. A nonempty output file alone does not prove success.

Run a trusted job with its streams redirected to separate files. Use an if/else form that preserves the original status in the else branch. The pattern if ! command negates the status, so reading $? inside that branch would observe the negation rather than the failed command’s code.

Do not publish partial success

Write the job’s report output to a temporary file. On success, move that complete file into the published path. On failure, retain the previous report, keep diagnostics in the log, print a concise failure message to stderr and return the job’s nonzero status.

An EXIT trap cleans the temporary directory on either path. This is a small example of reliable automation under a scheduler, where nobody is watching the terminal. It does not install cron or a system service in the browser. The checker substitutes failing jobs that print partial output, proving that a plausible-looking file cannot bypass the success requirement.

Try an example.sh
if bash ./jobs/report.sh > example-output.txt 2> example-errors.txt; then
 printf 'Example job succeeded\n'
else
 status=$?;printf 'Example job returned %d\n' "$status"
fi
YOUR TURN

Put it into practice.

Run the trusted jobs/report.sh in a child Bash. Capture its stderr exactly in job.log and its stdout in a temporary file. On exit 0, replace report.txt with the complete stdout and print Report published plus a newline. On nonzero exit, leave any prior report.txt unchanged, print Job failed: <status> plus a newline on stderr, and exit with the original status. Do not publish partial stdout or duplicate job diagnostics on your own stderr.

See an explained solution
One way to solve it.sh
tmp=$(mktemp -d "${TMPDIR:-/tmp}/rocks-job.XXXXXX") || exit 1
trap 'rm -rf "$tmp"' EXIT
if bash ./jobs/report.sh > "$tmp/report.txt" 2> job.log; then
 mv "$tmp/report.txt" report.txt || exit 1
 printf 'Report published\n'
else
 status=$?
 printf 'Job failed: %d\n' "$status" >&2
 exit "$status"
fi

The success branch publishes a complete report, while the failure branch preserves the previous result and the original exit code. Diagnostics remain available in job.log without being mixed into structured report data.