Linux

Bash Script Works Manually but Fails in Cron? Diagnose It

Aseem Kishore
16 min read

The Back Room Tech is reader-supported. We may earn a commission when you buy through links on our site. Learn more.

Your Bash script works when you run it by hand, but under cron it fails, hangs, or does nothing at all. It’s one of the most common scheduling problems on Linux, and the script itself is usually fine. Cron runs your job in a stripped-down, non-interactive environment. That environment has a different shell, a shorter PATH, no login files, possibly a different working directory, and no terminal.

Treat this as an environment-diff problem. Capture evidence of exactly how cron’s environment differs from your interactive shell, then change only the thing that differs. The reference throughout is the documented behavior in the crontab(5) manual page (retrieved 2026-10-25).

Prerequisites

  • A Linux system with a cron daemon installed. Common implementations include cronie, Vixie cron, and Debian’s cron package. Defaults vary by implementation and distro.
  • Shell access to the machine (local or SSH). It could be a VPS, a home server, a NAS, or a Raspberry Pi running backups.
  • Permission to edit the relevant crontab. Your own crontab needs no special rights. /etc/crontab and /etc/cron.d/ need root.
  • sudo access if the job runs as a different account.

Environment note: The commands below use conventions common to Debian/Ubuntu and RHEL/Fedora-family systems. Paths such as the Bash binary location, the cron service name, and log locations differ between distros. Verify each one locally before you rely on it.

Why Cron’s Environment Is Different

The crontab(5) page documents that cron sets only a few variables for each job: SHELL, HOME, LOGNAME, and a default PATH. HOME and LOGNAME come from the account database. On many implementations, SHELL defaults to /bin/sh, so you don’t get Bash unless you ask for it.

Cron doesn’t read your .bashrc, .bash_profile, or .profile. Anything those files set up is missing under cron. That includes aliases, PATH additions, exported API keys, and virtual-environment activation. Jobs also run with no attached terminal (TTY).

The default PATH is implementation-defined. The FreeBSD/Debian crontab(5) page documents /usr/bin:/bin. Don’t assume that value on every system.

The man7.org crontab(5) manual page scrolled to the section describing environment variables SHELL, PATH, HOME, and LOGNAME, with the paragraph on percent-sign (%) conversion to newline also visible or highlighted

You can read your own system’s version with:

man 5 crontab

Search inside the pager with /SHELL and /percent. That finds the relevant sections for your installed implementation.

Quick Diagnosis: A Six-Step Sequence

Work through these steps in order. Each one gathers evidence before you change anything.

Step 1: Back Up the Current Crontab

Do this before you touch anything:

# Saves your current user crontab to a timestamped file in your home directory
crontab -l > ~/crontab-backup-$(date +%F-%H%M).txt

The % signs are fine here because you’re typing in an interactive shell, not in a crontab line. If you have no crontab yet, you’ll see something like no crontab for youruser.

Warning: crontab somefile replaces your entire crontab with that file’s contents. crontab -r deletes it without confirmation on many systems, and the r key sits right next to e. Always edit with crontab -e, and only restore from a backup file on purpose.

Step 2: Inspect What’s Actually Scheduled

crontab -l

Example output (illustrative only):

MAILTO=""
# m h dom mon dow command
*/15 * * * * /home/youruser/bin/sync-photos.sh
0 2 * * * /home/youruser/bin/backup.sh >> /home/youruser/logs/backup.log 2>&1
Illustrative example only — output of crontab -l showing two small example jobs with the five schedule fields and the command field visually distinguished, labeled "Illustrative example only"

Confirm three things. The schedule is what you expect. The script path is absolute. You know whether output goes anywhere at all.

Step 3: Confirm the Cron Daemon Is Running

The service name varies. Debian and Ubuntu commonly use cron. RHEL, Fedora, and many others use crond. List what exists rather than guessing:

# Lists installed unit files with "cron" in the name
systemctl list-unit-files '*cron*'

Then check the status of the name you found:

systemctl status cron

Look for active (running). If the unit is inactive or the name isn’t found, try crond or whatever name the previous command listed.

Step 4: Capture the Cron Environment Safely

Don’t dump the full environment with env or printenv into a log file. Those values can include tokens and passwords. Capture only the variables that matter, plus the names of everything else that’s exported.

Create /home/youruser/bin/cron-env-check.sh:

#!/bin/bash
# /home/youruser/bin/cron-env-check.sh
# Usage: cron-env-check.sh LABEL
# Records only non-secret diagnostic values, then exported variable NAMES (no values).

label="${1:-unknown}"
out="$HOME/cron-env-$label.txt"

{
  echo "SHELL=$SHELL"
  echo "PATH=$PATH"
  echo "HOME=$HOME"
  echo "LOGNAME=$LOGNAME"
  echo "working dir: $(pwd)"
  echo "identity: $(id)"
  echo "umask: $(umask)"
  if [ -t 0 ]; then echo "TTY: yes"; else echo "TTY: no"; fi
  echo "/bin/sh probe (explicitly invoked): $(/bin/sh -c 'printf "%s" "$0"' 2>&1)"
  echo "/bin/bash probe (explicitly invoked): $(/bin/bash -c 'printf "%s" "$0"' 2>&1)"
  for tool in bash python3 rsync curl; do
    echo "which $tool: $(command -v "$tool" || echo NOT FOUND)"
  done
  echo "--- exported variable names (values omitted) ---"
  compgen -e | sort
} > "$out" 2>&1

Make it executable for your user only. Skip world-writable modes:

chmod 700 /home/youruser/bin/cron-env-check.sh

Run it once interactively:

/home/youruser/bin/cron-env-check.sh interactive

Next, add a temporary line with crontab -e. Replace /bin/bash with the output of command -v bash on your system:

* * * * * /bin/bash /home/youruser/bin/cron-env-check.sh cron

The SHELL=$SHELL line in each file reflects cron’s own SHELL variable — the interpreter cron would use to run the command field if you hadn’t pinned it to /bin/bash yourself. Don’t rely on the script’s own $0 to tell you what shell cron chose; since the crontab line above already names /bin/bash explicitly, $0 would only confirm that Bash ran it, not what cron’s default would have been. The two probe lines report what /bin/sh and /bin/bash each say about their own $0 when you invoke them directly — a controlled test of a named shell, not automatic discovery of cron’s default. Wait a minute or two, then compare the two files:

diff ~/cron-env-interactive.txt ~/cron-env-cron.txt

Example output (synthetic, for illustration):

1c1
< SHELL=/bin/bash
---
> SHELL=/bin/sh
3c3
< PATH=/home/youruser/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
---
> PATH=/usr/bin:/bin
9c9
< TTY: yes
---
> TTY: no

Remove the temporary * * * * * line with crontab -e once you have your evidence. Otherwise it keeps firing every minute. Every difference in that diff is a suspect.

Step 5: Reproduce as the Real Cron Account

If the job runs as a service account, test as that account. Use a cleared environment that approximates cron:

# env -i starts with an empty environment; we then set only what cron typically provides
# </dev/null removes interactive stdin, like cron
sudo -u svc-backup env -i \
  HOME=/home/svc-backup LOGNAME=svc-backup SHELL=/bin/sh PATH=/usr/bin:/bin \
  /bin/sh -c '/opt/scripts/backup.sh' </dev/null

Adjust HOME and PATH to match what your Step 4 capture recorded. It’s only an approximation of cron. Still, it surfaces most PATH, permission, and prompt problems right away.

Step 6: Check the Scheduler Log

Confirm cron actually tried to run the job. Locations vary:

# systemd-based systems (use the service name you found in Step 3)
journalctl -u cron --since "1 hour ago"

On systems that log to files, check /var/log/syslog (common on Debian/Ubuntu with rsyslog) or /var/log/cron (common on RHEL-family systems). A log entry showing the command means cron fired it. In that case, the problem is inside the job’s environment. No entry points to the schedule, the crontab syntax, or the daemon itself.

Common Issues and Solutions

Problem: Bash Syntax Fails Because Cron Uses /bin/sh

Symptoms:

  • Errors like [[: not found, Syntax error: "(" unexpected, or source: not found
  • Works in your terminal, where your login shell is Bash

Why it happens: The SHELL crontab variable often defaults to /bin/sh. On Debian and Ubuntu, /bin/sh is commonly dash. Dash doesn’t support Bash-only features such as arrays, [[ ]], source, or set -o pipefail. If your crontab line has Bash syntax, or calls a script with no shebang, the POSIX shell interprets it.

Fix: Find your Bash path, since it differs by system:

command -v bash

Give the script an explicit shebang:

#!/usr/bin/env bash

Then invoke it explicitly in the crontab so nothing depends on SHELL:

0 2 * * * /bin/bash /home/youruser/bin/backup.sh

Verify: Re-run the environment capture. Your script now runs under Bash regardless of cron’s configured SHELL.

Problem: “Command Not Found” Only Under Cron

Symptoms:

  • rsync: command not found, python3: not found, or tools in /usr/local/bin or ~/.local/bin missing
  • The which lines in your capture show NOT FOUND

Why it happens: Cron’s default PATH is much shorter than your login PATH. Your shell startup files added the extra directories, and cron never reads them.

Fix: Use absolute paths inside the script:

command -v rsync
/usr/bin/rsync

Or set a literal PATH at the top of your crontab. The crontab(5) page documents that environment assignments are not expanded. So $HOME/bin or ~/bin won’t work in the assignment.

# Literal values only — no $HOME, no ~
PATH=/home/youruser/.local/bin:/usr/local/bin:/usr/bin:/bin

Verify: The which lines in ~/cron-env-cron.txt now resolve after the next run.

Problem: Script Can’t Find Its Relative Files

Symptoms:

  • No such file or directory for ./config.ini or data/
  • Output files appear in your home directory instead of the project folder

Why it happens: Cron doesn’t start in the directory you ran the script from. Oracle’s crontab documentation describes starting in the user’s home directory. Check the working dir line in your own capture rather than assuming that applies everywhere.

Fix: Pin the directory at the top of the script:

cd /opt/projects/photo-sync || exit 1   # exit if the directory is missing instead of running in the wrong place

Or do it in the crontab line:

*/15 * * * * cd /opt/projects/photo-sync && /bin/bash ./sync.sh

Verify: Output files land where expected after the next scheduled run.

Problem: No Error Output Anywhere

Symptoms:

  • The job clearly didn’t work, but nothing shows on screen or in any file
  • On Debian/Ubuntu, the log may show (CRON) info (No MTA installed, discarding output)

Why it happens: Cron mails a job’s stdout and stderr to the crontab owner, or to the address in MAILTO. If no mail transfer agent (MTA) is installed, or nobody reads local mail, the output disappears. MAILTO="" explicitly disables mail.

Fix: Redirect both streams to a log you control:

# >> appends; 2>&1 sends stderr to the same place as stdout
0 2 * * * /bin/bash /home/youruser/bin/backup.sh >> /home/youruser/logs/backup.log 2>&1

Make sure the log directory exists and the job’s account can write to it.

Verify: After the next run, tail -n 20 /home/youruser/logs/backup.log shows real output or errors.

Problem: A Line With % Behaves Strangely

Symptoms:

  • Syntax error: Unterminated quoted string
  • A date +%F filename comes out truncated, or the command runs only partly

Why it happens: The crontab(5) page documents that an unescaped % in the command field becomes a newline. Everything after the first % goes to the command as standard input.

Fix: Escape each literal % with a backslash. This one is broken:

0 2 * * * /usr/bin/tar -czf /backup/home-$(date +%F).tar.gz /home/youruser

This one is correct:

0 2 * * * /usr/bin/tar -czf /backup/home-$(date +\%F).tar.gz /home/youruser

The cleaner option is to move the date logic into the script, where % has no special meaning.

Verify: The archive appears with the full date in its name.

Problem: Variables From .bashrc Are Missing

Symptoms:

  • API calls fail with auth errors
  • A Python virtualenv or nvm Node version isn’t active

Why it happens: Cron doesn’t source login or interactive startup files.

Fix: Load only what the script needs from a restricted file:

chmod 600 /home/youruser/.config/backup.env   # readable only by the owner
# Inside the script
set -a                                  # auto-export variables defined while sourcing
. /home/youruser/.config/backup.env
set +a

For virtualenvs, call the interpreter directly, for example /opt/projects/app/.venv/bin/python. Never log the values you load.

Verify: The variable name appears in the exported variable names section of your capture, and the job authenticates.

Problem: Job Hangs Waiting for Input

Symptoms:

  • sudo: a terminal is required to read the password
  • the input device is not a TTY from docker run -it
  • SSH or rsync over SSH stalls on a passphrase or host-key prompt

Why it happens: There’s no TTY under cron, so anything that prompts will block or fail.

Fix: Use non-interactive equivalents. Drop -t from docker run/docker exec. For SSH, use a key dedicated to the job, and set up host-key verification deliberately instead of accepting whatever key shows up on first connect. Verify the target host’s key fingerprint through a trusted out-of-band channel — the hosting provider’s control panel, a colleague who already confirmed it, or a similar source — then record that verified key in a known_hosts file dedicated to the job account, not the account’s default ~/.ssh/known_hosts:

ssh-keyscan -t ed25519 remote.example.com >> /home/svc-backup/.ssh/job_known_hosts
# Compare the resulting fingerprint against the one you verified out-of-band before trusting this file

Then pin the job to that file and make failure explicit instead of letting it hang:

0 2 * * * /usr/bin/ssh -i /home/svc-backup/.ssh/job_key \
  -o UserKnownHostsFile=/home/svc-backup/.ssh/job_known_hosts \
  -o StrictHostKeyChecking=yes -o BatchMode=yes \
  -l svc-backup remote.example.com '/opt/scripts/remote-task.sh'

Keep job_key and job_known_hosts readable only by the job account (chmod 600). BatchMode=yes makes SSH fail immediately rather than wait on any prompt, including one caused by an unexpected host-key change — which is exactly what you want a noninteractive job to do instead of silently accepting a new key. Pass other tools’ batch or --yes flags the same way. For privileged steps, grant a narrowly scoped sudoers rule for one command. Don’t run the whole job as root, and don’t relax sudo restrictions globally.

Verify: The Step 5 env -i ... </dev/null test completes without prompting.

Problem: /etc/crontab or /etc/cron.d Entry Never Runs

Symptoms:

  • The same line works in crontab -e but not in /etc/cron.d/backup
  • The log shows errors about an unknown user, or nothing at all

Why it happens: System-wide files need an extra username field between the schedule and the command. Personal crontabs don’t use it. On Debian-based systems, files in /etc/cron.d must also follow run-parts naming rules, so no dots in the filename. Check your local man 5 crontab. Ownership and permission rules also apply. Files are typically root-owned and not group- or world-writable.

Fix:

# /etc/cron.d/photo-backup
# m h dom mon dow USER command
0 2 * * * svc-backup /bin/bash /opt/scripts/backup.sh >> /var/log/photo-backup.log 2>&1

Verify: Run the Step 5 sudo -u svc-backup test. Then confirm the scheduler log shows the job firing as svc-backup.

Error Messages Quick Reference

Error messageLikely causeFix
[[: not found / Syntax error: "(" unexpectedBash syntax run by /bin/shBash shebang + explicit /bin/bash invocation
source: not foundPOSIX shell lacks sourceUse . or run under Bash
rsync: command not foundShort cron PATHAbsolute path or literal PATH= line
No such file or directory (relative path)Unexpected working directorycd /abs/path || exit 1
No MTA installed, discarding outputNo mail system for job outputRedirect >> log 2>&1
Unterminated quoted stringUnescaped % in crontabEscape as \%
sudo: a terminal is required to read the passwordNo TTY under cronScoped sudoers rule or remove sudo
the input device is not a TTYdocker ... -t under cronDrop -t
Permission deniedWrong account or file modeTest with sudo -u; fix ownership

Platform-Specific Notes

Debian and Ubuntu: /bin/sh is commonly dash, so Bash-isms fail loudly. The service is usually cron. Logs are typically in journalctl -u cron or /var/log/syslog. User crontabs usually live under /var/spool/cron/crontabs/. Don’t edit that directory directly.

RHEL, Fedora, and derivatives: These typically ship cronie with the service crond. Logs commonly go to /var/log/cron or the journal. /bin/sh is usually Bash running in POSIX mode, so some Bash-isms happen to work. Don’t rely on that. Also check SELinux denials with ausearch -m avc -ts recent rather than disabling SELinux.

Arch and minimal systems: A cron daemon may not be installed by default. The POSIX crontab(1p) page describes the portable baseline. Implementation details come from whichever package you install.

Configuration Mistakes to Check

  • Expanding variables in assignments: PATH=$HOME/bin:/usr/bin isn’t expanded. Write the literal path.
  • Missing username in system files: /etc/crontab and /etc/cron.d/* need it, and user crontabs must not have it.
  • No trailing newline: Some implementations ignore the last line if the file doesn’t end with a newline. crontab -e usually handles this.
  • Relying on aliases: Aliases from .bashrc don’t exist under cron. Use full commands.
  • Overly broad fixes: Adding chmod 777 or switching to root hides the real cause and creates a new security problem.

Getting Help

When you ask on a forum or open a ticket, include:

  • Distro and version (cat /etc/os-release) and cron implementation (systemctl list-unit-files '*cron*')
  • The exact crontab line, with secrets redacted
  • The redacted diff from Step 4
  • The scheduler log lines around the run time, plus your job’s own log

Good places to ask are your distro’s forums and Unix & Linux Stack Exchange. The man pages help too: man7 crontab(5) and Ubuntu crontab(5).

Prevention Tips

  • Write cron-ready scripts from day one: Use a shebang, absolute paths, cd ... || exit 1, and explicit logging.
  • Test with env -i before scheduling: Five seconds of testing beats finding out at 2 a.m.
  • Back up before every edit: Run crontab -l > backup first, then use crontab -e.
  • Use dedicated service accounts: Give each job only the permissions it needs.
  • Protect the hardware too: Nightly jobs on a home server or NAS fail silently if the box rebooted mid-run. A UPS and output logging catch both kinds of failure.

Should You Switch to a systemd Timer?

Not necessarily. Cron works fine once you control its environment.

On systemd hosts, though, a .timer unit that activates a .service unit gives you a few extras. You can set WorkingDirectory=, User=, and Environment= explicitly in the unit. Logs go to the journal automatically (systemd.timer(5), SUSE timer guide). The trade-off is two unit files instead of one line, plus a steeper learning curve.

systemctl list-timers
journalctl -u myjob.service --since today
Illustrative example unit, not a real production job — output of systemctl status myjob.timer showing the next scheduled trigger time, followed by journalctl -u myjob.service log lines

Wrapping Up

When a Bash script works manually but fails in cron, the script is usually fine. The environment around it changed. Capture the diff first, then fix the specific gap: shell, PATH, working directory, missing variables, TTY, or identity. I’d keep the Step 4 capture script in ~/bin permanently, since it turns guesswork into a two-minute check.

StepActionApplies To
1Back up with crontab -l > fileAll crontabs
2–3Inspect jobs, confirm daemonAll systems
4Capture and diff the environment (no secrets)All jobs
5Reproduce with sudo -u + env -iService-account jobs
6Check scheduler logsDistro-specific locations
FixShebang, absolute paths, cd, redirects, \%Per diagnosed cause

Last updated: 2026-10-25 | Applies to cron (cronie, Vixie, Debian cron) on Linux

Sources