使用 Crontab 连接文件输出文本

Concatenate file output text with Crontab

我已经成功跟进这个问题,Using CRON jobs to visit url?,维护以下 Cron 任务:

*/30 * * * * wget -O - https://example.com/operation/lazy-actions?lt=SOME_ACCESS_TOKEN_HERE >/dev/null 2>&1

上面的 Cron 任务工作正常,它每 30 分钟定期访问 URL。

但是,访问令牌记录在 /home/myaccount/www/site/aToken.txt 中的文本文件中,aToken 文件是非常简单的一行文本文件,仅包含令牌字符串。

我尝试读取其内容并使用 cat 将其传递给 crontab 命令,如下所示:

*/30 * * * * wget -O - https://example.com/operation/lazy-actions?lt=|cat /home/myaccount/www/site/aToken.txt| >/dev/null 2>&1

但是,上面的解决方案一直未能运行 cronjob。

我在 Ubuntu 16.04

上使用 nano 使用 crontab -e 编辑 Cronjobs

这是一种快速解决方案,无需复杂的单行代码即可完全满足您的需求:

在您的 myaccount 中创建此文件 -- 如果您愿意,您也可以将其放入您的 bin 目录中,只需记住您放置它的位置,以便您可以从您的 [=14] 中调用它=].还要确保用户有权 read/write 访问 sh 文件所在的目录

wget.sh

#!/bin/bash

#simple cd -- change directory
cd /home/myaccount/www/site/  

#grab token into variable aToken
aToken=`cat aToken.txt`  

#simple cd -- move to wget directory
cd /wherever/you/want/the/wget/results/saved 

#Notice the $ -- This is how we let the shell know that aToken is a variable = $aToken
#wget -O - https://example.com/operation/lazy-actions?lt=$aToken
wget -q -nv -O /tmp/wget.txt https://example.com/operation/lazy-actions?lt=$aToken >/dev/null 2>/dev/null

# You can writle logs etc etc afterward here.  IE
echo "Job was successful" >> /dir/to/logs/success.log

然后只需像您已经在做的那样用您的 CRON 调用此文件。

*/30 * * * * sh /home/myaccount/www/site/wget.sh >/dev/null 2>&1

基于这个问题,Concatenate in bash the output of two commands without newline character,我得到了以下简单的解决方案:

wget -O - https://example.com/operation/lazy-actions?lt="$(cat /home/myaccount/www/site/aToken.txt)" >/dev/null 2>&1

它能够读取文本文件的内容,然后回显到命令流。