New FAMILUG

The PyMiers

Sunday 16 October 2016

[Backup] Ký tự % trong crontab

Một ngày mưa, viết crontab backup dữ liệu về máy, gặp ngay lỗi
unexpected EOF while looking for matching ``'
Tức tự dưng một ký tự kết thúc file (EOF) xuất hiện trong câu lệnh chứa đoạn
scp SOMEWHERE xxx-`date +%Y%m%d_%H%M%S`.tar.gz
Với Linux based OSes, ký tự % trong file crontab không có giá trị gì đặc biệt.

Theo doc Ubuntu manpage 5 crontab
The ``sixth'' field (the rest of the line) specifies the command to be run. The entire command portion of the line will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile.
Khi gõ man 5 crontab trên Ubuntu 16.04, ta có:

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 % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the crontab file.  Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input. There is no way to split a single command line onto multiple lines, like the  shell's trailing "\".
Xem online tại: http://manpages.ubuntu.com/manpages/xenial/en/man1/crontab.1posix.html
Tài liệu online của Ubuntu manpage không giống xem từ lệnh man, nó dùng nội dung của file man cung cấp bởi systemd-cron

Trên OSX, ký tự % cũng được xem như dấu xuống dòng (newline).
Theo man của OpenBSD:

The command field (the rest of the line) is the command to be run. The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the crontab. Percent signs (‘%’) 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. If the command field begins with ‘-q’, execution will not be logged. Use whitespace to separate ‘-q’ from the command.
Vì thế nên trên OSX,  nếu muốn thêm timestamp vào tên file backup, phải escape dấu %.
scp hvnaws:/var/lib/xxx/xxx.tar.gz /Users/hvn/backup/xxx_`date +\%Y\%m\%d_\%H\%M\%S`.tar.gz
PS:
để chạy lệnh scp ngon lành, cần chỉ rõ path của private SSH key mình sẽ sử dụng, bởi khi chạy trong crontab, các biến môi trường sẽ không được set như lệnh gõ trên shell bình thường.

Câu lệnh trên sẽ phải sửa thành
scp -i /Users/hvn/.ssh/mykey.pem ...

Hết.
Happy backup
HVN at FAMILUG dot ORG
Sài Gòn chiều mưa

No comments:

Post a Comment