パブリック IP をログ ファイルに cron する

パブリック IP をログ ファイルに cron する

cron を使用してパブリック IP をファイルに記録したいです。次のようになります:

2021-05-17T01:11:46 99.99.99.99
2021-05-17T01:12:46 99.99.99.99
2021-05-17T01:13:46 99.99.99.99

私がまとめたものは次のとおりです。

* * * * * { date +%FT%T | tr "\n" " "; curl https://ipinfo.io/ip -s ; echo "" ; } >> /home/mario/logs/pubip.log

sh プロンプトでは動作しますが、先頭にアスタリスクを付けて crontab -e に入力すると、次のエラーが発生します。

/bin/sh: 1: Syntax error: end of file unexpected (expecting "}")

OS: Ubuntu 20.04.2 LTS

*書式設定を処理するには、もっとエレガントな方法が必要です。私がフランケンシュタイン化したものは、かなりぎこちなく感じます。

答え1

結局、'%' 記号であることが判明しました。ドキュメントをもっと読むべきでした: crontab(5)

The "sixth" field (the rest of the line) specifies the command to
       be run.  The entire command portion of the line, up to a newline
       or a "%" character, will be executed by /bin/sh or by the shell
       specified in the SHELL variable of the cronfile.  A "%" character
       in the command, unless escaped with a backslash (\), will be
       changed into newline characters, and all data after the first %
       will be sent to the command as standard input.

最終的に機能した正しいcron行は

* * * * * { date +\%FT\%T | tr "\n" " "; curl https://ipinfo.io/ip -s ; echo "" ; } >> /home/mario/logs/pubip.log

とはいえ、@scimerman の提案に従って、読みやすさのためにこれをスクリプトに移動します。

答え2

再現できませんでした。cron のコマンドが大きすぎる場合は、別の cron スクリプト内にラップして、crontab から呼び出す方が効率的です。

$ cat ~/crontab.ip 
#!/bin/bash
{ date +%FT%T | tr "\n" " "; curl https://ipinfo.io/ip -s ; echo "" ; } >> ~/log.ip

私のcrontabは次のとおりです:

$ crontab -l
* * * * * ~/crontab.ip

動作するはずです。

答え3

cron システムにコマンドを配置する場合は、コマンドのフルパスを使用する必要があります。

すなわち、
日付すべきである/bin/日付
trすべきである/usr/bin/tr
カールすべきであるカーソル
エコーすべきであるエコー

関連情報