LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Learning Crontab (https://www.linuxquestions.org/questions/linux-newbie-8/learning-crontab-4175606528/)

krishnar 05-23-2017 01:40 PM

Learning Crontab
 
Hi All,

I have added my first cron job like this:

user@krishnar6:~$ crontab -l | grep -v "#"

* * * * * /home/user/test.sh

user@krishnar6:~$ cat /home/user/test.sh
#!/bin/bash
echo hello!
user@krishnar6:~$

I expected this job to run every minute and print hello output. But it never did. Can you please help me to fix the prob?

Krish

joe_2000 05-23-2017 01:44 PM

The script will print to stdout, which cron sends to the configured email account.
Unless you have configured that in a sensible way you will never see it.

Try redirecting the output to a file:

Code:

#!/bin/bash
echo "hello!" > /tmp/crontest.out

Also make sure the script is executable:
Code:

chmod +x /home/user/test.sh

krishnar 05-23-2017 01:48 PM

Quote:

Originally Posted by joe_2000 (Post 5714336)
The script will print to stdout, which cron sends to the configured email account.
Unless you have configured that in a sensible way you will never see it.

Try redirecting the output to a file:

Code:

#!/bin/bash
echo "hello!" > /tmp/crontest.out

Also make sure the script is executable:
Code:

chmod +x /home/user/test.sh

It worked!!

krishnar 05-23-2017 02:03 PM

I have modified my scrip like this:

user@krishnar6:~$ cat test.sh
#!/bin/bash
echo hello! > crontest.txt
mkdir /home/user/cron

The cron job creates the text file but NOT the folder. I am wondering why folder is not getting created.

joe_2000 05-23-2017 02:13 PM

Hmm, if all of this is happening as the same user this should actually work.

You can debug this by printing the output to a file. Change the crontab entry to

Code:

* * * * * /home/user/test.sh > /tmp/crontab.out 2>&1
The 2>&1 redirects stderr to stdout so that everything ends up in the out file.

Please post the content of /tmp/crontab.out after an (unsuccessfull) cron execution.

krishnar 05-23-2017 02:19 PM

user@krishnar6:~$ cat /tmp/crontab.out
/home/user/test.sh: line 3: mkdir: command not found
user@krishnar6:~$

joe_2000 05-23-2017 02:24 PM

Quote:

Originally Posted by krishnar (Post 5714354)
user@krishnar6:~$ cat /tmp/crontab.out
/home/user/test.sh: line 3: mkdir: command not found
user@krishnar6:~$

Ok, that explains. Cron has a reduced environment. That includes the content of the PATH variable. Therefore it does not find the mkdir executable.

Run
Code:

which mkdir
The output will probably be /bin/mkdir or /usr/bin/mkdir.

That is the full path to mkdir. Use that in the script. So e.g.:
Code:

/bin/mkdir /home/user/cron
For this reason it is good practice to always use absolute paths to commands in cronjobs.

krishnar 05-23-2017 02:32 PM

Thanks! That fixed the issue.


All times are GMT -5. The time now is 12:57 PM.