How to use tee command in crontab

I run crontab every 2 hours, I also want the log file of my bash output to be contained in a separate file.

Input:

0 0-23/2 * * * /tmp/sample.sh | tee /tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt 

Output:

 /bin/sh: -c: line 0: unexpected EOF while looking for matching `'' /bin/sh: -c: line 1: syntax error: unexpected end of file 
+4
source share
4 answers

The percent sign (%) is a special character in cron. Exit the% sign.

 0 0-23/2 * * * /tmp/sample.sh > /tmp/logfile_extract_$(date '+\%Y-\%m-\%d-\%H').txt 2>&1 
+2
source

Absolutely good reason to want this. And you can fully use tee if you want and can write the output to MAILTO . Take this crontab for example

 SHELL=/bin/bash MAILTO=someone@example.com 0 */2 * * * php /path/script.php | tee -a /path/log.$(date +"\%Y-\%m-\%d").txt 

Pay attention to what Lars said and escaped these percentage characters ( % )

+2
source

Why are you using tee in a cron job. To redirect output, you can:

 0 */2 * * * /tmp/sample.sh > /tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt 2>&1 

tee needs your tty to output the output, and there is no tty available with cron.

According to man tee :

The tee utility copies standard input to standard output, making it copy to zero or more files.

+1
source

From your comments above

 /tmp/logfile_extract_$(date '+%Y-%m-%d-%H').txt 

Is the problem 1) is / bin / sh really bash? I have seen operating systems where its โ€œsomething more than like,โ€ and therefore the bash syntax can throw it.

 0 */2 * * * /bin/bash -c '/tmp/sample.sh > /tmp/logfile_extract_$(date "+%Y-%m-%d-%H").txt 2>&1' 

may work in this case. Or you can consider the backlink or shell script called from cron, which simply executes

 /tmp/sample.sh > /tmp/logfile_extract_$(date "+%Y-%m-%d-%H").txt 2>&1 
+1
source

Source: https://habr.com/ru/post/1498173/


All Articles