简体   繁体   中英

Shell script doesn't run properly while running from crontab

I read the other related topics but they didn't help me.

I have a shell script which checks if my python script is not running,it will run it. Otherwise it will just skip and do nothing.

It totally works when I use: bash myshellscrip.sh And I get the result that I want which is doing some tasks and sending emails to some correspondents. However, when I try to run this particular shell script on crontab, it doesn't send out the emails and doesn't do the other tasks. I tried the following on crontab and none of them worked.

    * * * * * /bin/bash /path/to/my/script/myshellscrip.sh 
    * * * * * /bin/bash /path/to/my/script/myshellscrip.sh >> /some/other/path/output.txt

When I save the changes into 'output.txt' file, it creates the file but it doesn't send the emails or doing other tasks.

I also tried the option of reboot because I need this program to run at start up too, and this didn't work:

    @reboot /bin/bash /path/to/my/script/myshellscrip.sh

Does anyone know how to fix it?

EDIT:

As I was checking with the simplest shell scrip like:

    #!/bin/sh
    /usr/bin/python /home/pi/DCA/code.py

My crontab wouldn't have any output in my output.txt file although my code.py have something printing out, too.

However, when I use a very simple python code for example only a 'print' statement it will run and save the output into output.txt.

Seems like your shell script crashes / stops before it can do something (possibly due to the environment being different or permission issues). You can check /var/log/syslog to find out.

You could try removing /bin/bash , I don't think that's necessary?

Run the cron job in debug mode. for that, Add -x to the bash command on the cronjob and save their output in the file.

bash -x /path/to/script.sh >> /path/to/the/output.txt

You can find the problem.

Apparently crontab was running my script several times. So I tried to use different locking mechanisms to put a lock around my scrip but only using flock worked for me. In my crontab I added this line:

* * * * * /usr/bin/flock -n /tmp/ms.lockfile /bin/bash /path/to/my/script/myShellScript.sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM