I'm trying to use the functions defined in /home/my_username/.bashrc in a shell script that gets executed by crontab.
#crontab -l
# m h dom mon dow command * * * * * /bin/sh /home/my_username/CronTab_shell_script.sh >> /home/my_username/Desktop/file.log Let's say I have the mounted() function saved in
/home/my_username/.bashrc
function mounted(){ if mount|grep $1; then echo "mounted" else echo "not mounted" fi }How can I call and use the mounted() function from the
/home/my_username/CronTab_shell_script.sh 1 2 Answers
1. Run the correct shell
* * * * * /bin/sh .....You are not running bash, you are running sh, so you should not expect .bashrc to be loaded!
Try this instead:
* * * * * /bin/bash .....2. Work around Ubuntu's default .bashrc
Another problem might be that Ubuntu's default .bashrc script starts with this guard:
# If not running interactively, don't do anything
case $- in *i*) ;; *) return;;
esacAny lines you add below this will not be loaded by your cron script because cronjobs do not run in an interactive environment.
The solution: Put functions for scripts above this guard. Keep setup for the user below this guard.
3. Load the complete user login environment
On some systems I find its easiest to use --login to ensure the shell has the same things loaded that I have at the command line.
* * * * * bash --login /path/to/script.sh
* * * * * bash --login -c "your command here" Cron runs with a limited shell and won't have access to your regular environment.
You could put source /home/my_username/.bashrc at the beginning of /home/my_username/CronTab_shell_script.sh to make the function available.
You could also source your .bashrc in your crontab:
#crontab -l
# m h dom mon dow command * * * * * . /home/my_username/.bashrc; /bin/sh /home/my_username/CronTab_shell_script.sh >> home/my_username/Desktop/file.log 1