Skip to content
shellhacks.dev
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
Summarize in AI

A command with a Bash feature, like a [[ ]] test, works in a terminal and silently fails under cron.

Shell
cat > default.cron <<'EOF'
* * * * * [[ -n "$BASH_VERSION" ]] && echo bash > /tmp/default.txt || echo sh > /tmp/default.txt
EOF
cat > bash.cron <<'EOF'
SHELL=/bin/bash
* * * * * [[ -n "$BASH_VERSION" ]] && echo bash > /tmp/bash.txt || echo sh > /tmp/bash.txt
EOF
useradd -m alice; useradd -m bob
crontab -u alice default.cron
crontab -u bob bash.cron
sleep 65
cat /tmp/default.txt /tmp/bash.txt
Text
sh
bash

Each job line is passed to the shell named by the SHELL variable, and the default is /bin/sh, which is dash on Debian, so [ is a syntax error and the || branch ran. The [crontab manual lists SHELL among the variables a crontab may set. With SHELL=/bin/bash the same test passes for the second user.

Setting the shell affects only the command string in the crontab, not any script it runs, which follows its own shebang line. Many scripts are better made to work under sh than served by a changed cron environment. The command also runs from the home directory, not the directory of the crontab.

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 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
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.