Skip to content
shellhacks.dev
Cron and Scheduling

Set PATH in a crontab

Set PATH on a line at the top of a crontab, because cron runs jobs with a minimal PATH of /usr/bin and /bin and a tool in /usr/local/bin is not found.

1 min read
Summarize in AI

A script finds its tools in a terminal and fails under cron with "not found" for something installed in /usr/local/bin.

Shell
printf '#!/bin/sh\necho tool ran\n' > /usr/local/bin/mytool
chmod +x /usr/local/bin/mytool
cat > nopath.cron <<'EOF'
* * * * * mytool > /tmp/nopath.txt 2>&1
EOF
cat > withpath.cron <<'EOF'
PATH=/usr/local/bin:/usr/bin:/bin
* * * * * mytool > /tmp/withpath.txt 2>&1
EOF
useradd -m alice; useradd -m bob
crontab -u alice nopath.cron
crontab -u bob withpath.cron
sleep 65
cat /tmp/nopath.txt /tmp/withpath.txt
Text
/bin/sh: 1: mytool: not found
tool ran

Cron does not read your login files and starts each job with a short environment. On Debian the default PATH is /usr/bin:/bin, as the crontab manual says, so mytool in /usr/local/bin was not found for the first user. A NAME=value line at the top of the file is applied to every job in it, and the second user's job found the tool.

The setting applies to the whole crontab, not to the lines below it only. Another way is the full path in the command, which is clearer and survives a change of cron. Do not put $PATH on the right side: cron does not expand variables in these lines.

Share

More snippets

Cron and Scheduling

Escape percent signs in a cron command

A percent sign in a crontab command ends the command and feeds the rest to stdin. Escape it with a backslash, or the date call below breaks at once.

1 min read
Cron and Scheduling

Set the shell for cron

Cron runs jobs with /bin/sh. Set SHELL=/bin/bash at the top of the crontab to use Bash features such as [[ ]], arrays and process substitution.

1 min read
Cron and Scheduling

Send cron output to a file

Send cron output to a log with >> file 2>&1. The order matters: 2>&1 before the file leaves stderr behind, and cron mails or drops it.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.