shell 生成日志的几种方法

一、tee

## test_log.sh

set -x
echo $0
s=`dirname $0`
echo $s

# 在脚本路径执行脚本
bash -x test_log.sh 
+ set -x
+ echo test_log.sh
test_log.sh
++ dirname test_log.sh
+ s=.
+ echo .
.

# 在脚本上一层目录执行脚本
bash -x test_dir/test_log.sh 
+ set -x
+ echo test_dir/test_log.sh
test_dir/test_log.sh
++ dirname test_dir/test_log.sh
+ s=test_dir
+ echo test_dir
test_dir

# 从根目录处执行此文件
bash -x /home/xxx/test_dir/test_log.sh 
+ set -x
+ echo /home/xxx/test_dir/test_log.sh
/home/xxx/test_dir/test_log.sh
++ dirname /home/xxx/test_dir/test_log.sh
+ s=/home/xxx/test_dir
+ echo /home/xxx/test_dir
/home/xxx/test_dir

## 以上明白 $0指当前文件且带有与当前位置相对的路径;dirname可以获得当前文件的父路径也是相对当前位置。

bash -x test_dir/test_log.sh | tee test_dir/log.log
+ set -x
+ echo test_dir/test_log.sh
test_dir/test_log.sh
++ dirname test_dir/test_log.sh
+ s=test_dir
+ echo test_dir
test_dir

cat test_dir/log.log 
test_dir/test_log.sh
test_dir

二、>>

bash -x test_dir/test_log.sh >> test_dir/log1.log
+ set -x
+ echo test_dir/test_log.sh
++ dirname test_dir/test_log.sh
+ s=test_dir
+ echo test_dir

cat test_dir/log1.log 
test_dir/test_log.sh
test_dir


### 注意>> 与 >的区别
bash -x test_dir/test_log.sh >> test_dir/log1.log
+ set -x
+ echo test_dir/test_log.sh
++ dirname test_dir/test_log.sh
+ s=test_dir
+ echo test_dir

cat test_dir/log1.log 
test_dir/test_log.sh
test_dir
test_dir/test_log.sh
test_dir

bash -x test_dir/test_log.sh > test_dir/log1.log
+ set -x
+ echo test_dir/test_log.sh
++ dirname test_dir/test_log.sh
+ s=test_dir
+ echo test_dir

cat test_dir/log1.log 
test_dir/test_log.sh
test_dir

# 很明显
>写入,覆盖掉原有的;
>>继续添加,原来的还存在

三、实例:

#!/bin/bash
#文件名:test.sh
name="test-date-log"
echo $name

echo "BACKUP DATE:" $(date +"%Y-%m-%d %H:%M:%S")

DATE=`date '+%Y%m%d-%H%M%S'`
echo $DATE

LogNameDATE=`date '+%Y%m%d'`

echo " " >> log$LogNameDATE.log
echo "———————————————–" >> log$LogNameDATE.log
echo "BACKUP DATE:" $(date +"%Y-%m-%d %H:%M:%S") >> log$LogNameDATE.log
echo "———————————————– " >> log$LogNameDATE.log
#将当前时间和包含换行符的文本内容输出到文件
echo -e $(date) "\nHello World !" >> test.txt

#将当前时间(格式化)和包含换行符的文本内容输出到文件
echo -e `date '+%Y-%m-%d %H:%M:%S %A'` "\nHello World !" >> test.txt
#同上,简化版。
echo -e `date '+%F %T %A'` "\nHello World !" >> test.txt

#输出到以日期格式文件名
echo -e $(date) "\nHello World !" >> test`date +'%Y-%m-%d'`.txt

四、参考文档

1、https://www.cnblogs.com/smbx-ztbz/p/4607007.html

2、https://www.jb51.net/article/108720.htm

3、https://www.cnblogs.com/xiongzaiqiren/p/11413242.html

4、https://www.jb51.net/article/108725.htm

5、https://www.cnblogs.com/clnchanpin/p/6896178.html

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值