我已经在bash脚本中编写了2种日志记录方法,如下所示:
# Function to log information
function print_info() {
format="$1"
shift
printf "$(date +'%F %T') ${SCRIPTNAME}: INFO: $format\n" "$@" | tee -a ${LOGFILE};
}
# Function to log error
function print_error() {
format="$1"
shift
printf "$(date +'%F %T') ${SCRIPTNAME}: ERROR: $format\n" "$@" | tee -a ${LOGFILE} >&2;
}
并将以下消息定义为:
BACKUP_DIR_INFO="All the contents of directory %s are compressed to %s."
BACKUP_FILE_INFO="File %s is compressed at path %s."
ERROR_FILE_NOT_EXIST="File or directory %s does not exist."
从我的脚本中,我正在使用上述2种方法,如下所示:
function tarIt() {
FILE_NAME=$1
TAR_FILE_NAME=$2
if ! ([ -f $FILE_NAME ] || [ -d $FILE_NAME ]);
then
print_error $ERROR_FILE_NOT_EXIST $FILE_NAME
else
if [[ -f $FILE_NAME ]]
then
print_info "$BACKUP_FILE_INFO" "$FILE_NAME" "$BACKUP_DIR"
else
print_info "$BACKUP_DIR_INFO" "$FILE_NAME" "$TAR_FILE_NAME"
fi
fi
}
我tarIt
用2个文件名两次调用了该函数,其中一个不存在,另一个不存在,但是得到的输出如下所示:
2015-03-15 09:42:46 : ERROR: File
2015-03-15 09:42:46 : INFO: All the contents of directory /opt/mgtservices/relay/logs are compressed to /root/backup/relay_logs.tar.gz.
错误字符串未完全打印。
没有得到原因。甚至我尝试对其他消息使用方法print_error,但仅打印字符串的第一个单词。后面的部分则忽略了。
就像@Biffen在评论中说的那样,在所有变量引用周围加上双引号。当此命令运行时:
print_error $ERROR_FILE_NOT_EXIST $FILE_NAME
外壳将其扩展为:
print_error File %s is compressed at path %s. /path/to/nonexistent/file
...,因此print_error函数将“ File”作为$ 1接收,将其用作格式字符串,您将得到无意义的输出。顺便说一句,将数据(日期和脚本名称)嵌入格式字符串中也是一个坏主意;使用%s
并将它们添加到字段部分:
printf "%s %s: INFO: $format\n" "$(date +'%F %T')" "$SCRIPTNAME" "$@" | tee -a "$LOGFILE"
请注意,我还自由引用了$ LOGFILE的引用。除非有特殊原因,否则请养成将变量引用放在双引号中的习惯。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句