Bash script runs manually, but fails on crontab

后端 未结 5 942
逝去的感伤
逝去的感伤 2020-12-06 01:14

I\'m a newbie to shell scripting. I have written a shell script to do incremental backup of MySQL database.The script is in executable format and runs successfully when exec

相关标签:
5条回答
  • 2020-12-06 01:41
    1. In your crontab file your script entry can have

      * * * * * /bin/bash /path/to/your/script
      
    2. Make sure to use full paths in your script. I have had a look through it and I have not seen any but just in case I missed it.

    0 讨论(0)
  • 2020-12-06 01:42

    Another more generic way is to have cron run the user's bash logon process. In addition to the PATH, this will also pick up any LD_LIBRARY_PATH, LANG settings, other environment variables, etc. To do this, code your crontab entry like:

    34  12  * * *   bash -l /home/db-backup/mysqlbackup.sh
    
    0 讨论(0)
  • 2020-12-06 01:54

    Just import your user profile in the beginning of the script.

    i.e.:

    . /home/user/.profile
    
    0 讨论(0)
  • 2020-12-06 02:01

    The problem is probably that your $PATH is different in the manual environment from that under which crontab runs. Hence, which can't find your executables. To fix this, first print your path in the manual environment (echo $PATH), and then manually set up PATH at the top of the script you run in crontab. Or just refer to the programs by their full path.

    Edit: Add this near the top of your script, before all the which calls:

    export PATH="/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/mysql/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin"
    
    0 讨论(0)
  • 2020-12-06 02:04

    My Issue was that I set the cron job in /etc/cron.d (Centos 7). It seems that when doing so I need to specify the user who executes the script, unlike when a cronjob is entered at a user level.

    All I had to do was

    */1 * * * * root perl /path/to/my/script.sh
    */5 * * * * root php /path/to/my/script.php
    

    Where "root" states that I am running the script as root. Also need to make sure the following are defined at the top of the file. Your paths might be different. If you are not sure try the command "which perl", "which php".

    SHELL=/bin/bash
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    
    0 讨论(0)
提交回复
热议问题