crontab执行shell脚本报错:python: command not found
This is a super common issue—even when you set SHELL=/bin/bash in crontab and specify the shebang in your script, cron runs with a very limited default PATH that usually doesn't include the directory where your Python installation lives. Here are three solid fixes to get your backup working:
Use Python's absolute path (most reliable)
First, find exactly where Python is installed on your system by running this in your regular terminal:which python # Or use `which python3` if you're using Python 3Let's say the output is
/usr/bin/python3. Update your shell script's command to use this full path instead of justpython:/usr/bin/python3 -m grafana_backup.cli save --config $settings_fileThis bypasses any PATH issues entirely since you're telling cron exactly where to find Python.
Set PATH directly in your crontab
Open your crontab for editing withcrontab -e, then add a PATH line at the top (alongside your SHELL setting) that includes the directory where Python lives. For example:SHELL=/bin/bash PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin # Your scheduled job below 0 2 * * * /full/path/to/your/backup_script.shMake sure the PATH includes the directory from your
which pythonoutput (e.g., if Python is in/usr/bin, that's already included above).Add PATH to your shell script
If you don't want to mess with crontab settings, you can define the PATH at the top of your backup script:#!/bin/bash # Add necessary directories to PATH export PATH="/usr/local/bin:/usr/bin:/bin:$PATH" # Run the backup command python -m grafana_backup.cli save --config $settings_fileThis ensures the script loads the full PATH it needs before trying to execute Python.
I'd recommend the first option (absolute path) as it's the most resilient to future environment changes.
内容的提问来源于stack exchange,提问作者Alex Romero

