로그 파일에 대한 Cron 공용 IP

로그 파일에 대한 Cron 공용 IP

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: 우분투 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 시스템에 명령을 넣을 때 명령의 전체 경로를 사용해야 합니다.

즉,
날짜해야한다/빈/날짜
tr해야한다/usr/bin/tr
곱슬 곱슬하다해야한다/usr/빈/컬.
에코해야한다/usr/빈/에코

관련 정보