0

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
  • 1
    The easiest way is to put this function into the body of CronTab_shell_script.sh :) – pa4080 Sep 13 '17 at 12:09
4

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;;
esac

Any 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"
2

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
  • 1
    +1, but I think the Shell must be bash, it should be declared into the beginning of the script as #!/bin/bash and /bin/sh should be removed from the cron job. Also, maybe, the function should be exported after its definition in .bashrc : export -f mounted. – pa4080 Sep 13 '17 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.