brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: env -i runs a command with an empty environment, like cron and systemd do

Linux
~/tips/tip-linux-env-i-clean-environment

env -i ./backup.sh

Reproduce the 'works in my shell, fails in cron' problem on purpose.

A script that works in your terminal and fails from cron usually depends on something in your environment: a PATH entry, a variable from your profile, a language setting. env -i lets you test it without that safety net.

env -i ./backup.sh

-i starts the command with no environment variables at all. Run env -i bash -c env to see how little is left: only the few variables bash sets for itself. That is harsher than cron, which still sets a short PATH, HOME and SHELL, so add back what the real runner provides:

env -i PATH=/usr/bin:/bin HOME=/root SHELL=/bin/sh ./backup.sh

If the script fails now with command not found or a missing variable, you found the cause, and you can fix it in the script itself by setting PATH at the top or by using full paths.

I find this quicker than editing the crontab, waiting a minute and reading mail. It also helps for systemd services, which start with a small environment of their own.

Leave out -i and env instead adds or changes single variables for one command, like env TZ=UTC date. With -u NAME you remove one variable and keep the rest, for example env -u http_proxy curl example.com to test without a proxy.

An empty environment also has no LANG, so programs fall back to the C locale and may print different messages or sort differently than you are used to.

Further reading: env(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link