CodexBloom - Programming Q&A Platform

Bash script scenarios to read environment variables when executed in cron but works in terminal

šŸ‘€ Views: 27 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-14
bash cron environment-variables

I'm working with an scenario where my bash script runs fine in the terminal but fails to read specific environment variables when executed via cron. The script relies on a few variables that are set in my `.bashrc`. When I run it manually, everything works as expected. However, when I schedule it with cron, it fails with the following behavior: ``` behavior: MY_ENV_VAR not set ``` I have verified that my `crontab -e` contains the entry: ``` * * * * * /path/to/my_script.sh ``` I'm aware that cron jobs do not load the user's shell environment by default. I've tried sourcing the `.bashrc` at the beginning of my script like this: ```bash #!/bin/bash source ~/.bashrc # My script logic... ``` But I still get the same behavior. I've also tried setting the environment variable directly in the crontab entry: ``` MY_ENV_VAR=value * * * * * /path/to/my_script.sh ``` Still, the script does not recognize `MY_ENV_VAR`. I've checked for typos and confirmed that `MY_ENV_VAR` is indeed set in my terminal session. Can anyone shed light on why my script behaves differently under cron, and how I can make it recognize the environment variables? I’m using Ubuntu 22.04, and my script is intended to perform backups, which is critical for my workflow. Any help would be greatly appreciated! This is part of a larger application I'm building. Has anyone else encountered this?