dr *_*ter 7 bash shell scripting logging
这是bash-fu向导的一个.不,实际上,我只是在开玩笑,除了我,你们都可能知道这个.
我正在尝试创建备份shell脚本.这个想法很简单:查找某个文件夹中的文件,超过7天,tar/gzip到另一个目录,然后删除它们.问题是,我不确定我是否有足够的权限在目标目录中创建tar/gzip文件.是否有任何(正确的)方法来检查文件是否已成功创建,如果是,则删除文件.否则,跳过该部分,不要破坏客户的数据.我听说他们不是很喜欢那个.
这是我到目前为止所拥有的:
01: #!/bin/bash
02:
03: ROOTDIR="/data/www"
04:
05: TAR="${ROOTDIR}/log/svg_out_xml/export_out_ack_$(date +%Y-%m-%d).tar"
06: cd ${ROOTDIR}/exchange/export/out_ack/
07: find . -mtime +7 -type f -print0 | xargs -0 tar -cf "${TAR}"
08: gzip ${TAR}
09: find . -mtime +7 -type f -print0 | xargs -0 rm -f
Run Code Online (Sandbox Code Playgroud)
基本上,我需要检查第7行和第8行是否一切正常,如果是,执行9.
另外,我想制作这些操作的日志文件,所以我知道一切都很顺利(这是一个夜间的cron工作).
Ide*_*lic 12
对于日志记录,您可以安排在标准输出和/或标准错误上写入的所有输出转到文件.这样,您不需要重定向每个命令的输出:
# Save standard output and standard error
exec 3>&1 4>&2
# Redirect standard output to a log file
exec 1>/tmp/stdout.log
# Redirect standard error to a log file
exec 2>/tmp/stderr.log
# Now the output of all commands goes to the log files
echo "This goes to /tmp/stdout.log"
echo "This goes to /tmp/stderr.log" 1>&2
...
# Print a message to the original standard output (e.g. terminal)
echo "This goes to the original stdout" 1>&3
# Restore original stdout/stderr
exec 1>&3 2>&4
# Close the unused descriptors
exec 3>&- 4>&-
# Now the output of all commands goes to the original standard output & error
...
Run Code Online (Sandbox Code Playgroud)
要仅在前一个命令成功时执行命令,您可以使用条件链接它们:
# Execute command2 only if command1 succeeds, and command3 only if both succeed:
command1 && command2 && command3
# Execute command2 only if command1 fails
command1 || command2
Run Code Online (Sandbox Code Playgroud)
所以你可以做的事情
{ find . -mtime +7 -type f -print0 | xargs -0 tar -cf "${TAR}" &&
gzip ${TAR} &&
find . -mtime +7 -type f -print0 | xargs -0 rm -f } ||
{ echo "Something failed" 1>&2; exit 1 }
Run Code Online (Sandbox Code Playgroud)
或提供日志输出中的详细信息:
find . -mtime +7 -type f -print0 | xargs -0 tar -cf "${TAR}" ||
{ echo "find failed!!" 1>&2; exit 1 }
gzip ${TAR} ||
{ echo "gzip failed!!" 1>&2; exit 1 }
find . -mtime +7 -type f -print0 | xargs -0 rm -f ||
{ echo "cleanup failed!!" 1>&2; exit 1}
Run Code Online (Sandbox Code Playgroud)
对于日志记录,您可以用大括号包装脚本的各个部分,并将stdout重定向到日志文件:
{
script_command_1
script_command_2
script_command_3
} >> /path/to/log_file
Run Code Online (Sandbox Code Playgroud)
简单的方法,但没有明确的错误消息添加-e
到shebang,即#!/bin/sh -e
如果命令失败将导致shell退出..
不过,Cron应该通过邮件给你一个错误信息.
如果你想要完整的备份计划,我建议你使用已经制作的东西.那里有一堆,大多数工作得很好.