欢迎光临散文网 会员登陆 & 注册

Linux⽤⼾注意!这个技巧让你的脚本输出永不丢失

2023-08-17 15:14 作者:微思网络  | 我要投稿



对于⼴⼤的Linux系统管理员来说,是否有过这样的经历:在 crontab 计划任务中运⾏了⼀个脚本,然后希望查看其输出,却因没有合适的记录⽅式⽽感到困扰?

有没有想过让脚本运⾏的所有输出⾃动保存,以便于你在需要时随时查看?

今天,我将向你展⽰⼀个⽅法,让你得⼼应⼿。

⾸先,我们需要⼀个脚本,我准备了⼀个名为 disktest.sh 的脚本,它的功能是创建⼀个⽂件并进⾏各种块⼤⼩的读写测试。脚本内容如下:

#!/bin/bash
echo "creating a file to work with"
dd if=/dev/zero of=/var/tmp/infile count=1175000
for bs in 1k 2k 4k 8k 16k 32k 64k 128k 256k 512k 1M 2M 4M 8M
do
echo "Testing block size = $bs"
dd if=/var/tmp/infile of=/var/tmp/outfile bs=$bs
echo ""
done
rm /var/tmp/infile /var/tmp/outfile

让这个脚本每分钟运⾏⼀次,并将所有的输出保存到⽇志中

[root@localhost ~]# crontab -e
* * * * * /root/disktest.sh 2>&1 | logger -t disktest

意思是,每分钟运⾏⼀次/root/disktest.sh 脚本,并将所有的输出重定向(2>&1)到 logger 命令。


logger 命令将这些输出作为系统⽇志进⾏处理,并添加⼀个标签 "disktest"


这样,你的disktest.sh脚本的所有输出就会被⾃动保存到/var/log/messages⽂件中。

当你运⾏disktest脚本后,你可以在messages⽂件中看到类似以下内容,它记录了每⼀次的脚本输出:

Aug 109:58:02localhost disktest11048]: Testingblocksize=1K
Aug 109:58:02localhost disktest[11048]:587500+0recordsin
Aug 109:58:02 localhost disktest[11048]:587500+0 records out
Aug 109:58:02 localhost disktest[11048]:601600000 bytes(602M574MiB)copied, 533701 s,
1.1GB/s
Aug 109:58:02 localhost disktest[11048]:
Aug 109:58:02 localhost disktest[11048]:Testingblocksize=2k
Aug 109:58:03localhost disktest[11048]293750+0 recordsin
Aug 109:58:03localhost disktest[11048]:293750+0 records out
Aug 109:58:03localhost disktest[11048]:601600000 bytes(602 M574 MiB)copied.379295 s,
1.6 GB/s
Aug 109:58:03 localhost disktest[11048]:
Aug 109:58:03localhost disktest[11048]: Testingblocksize=4k
Aug 109:58:03localhost disktest[11048]: 146875+0 recordsin
Aug 109:58:03localhost disktest[11048]: 146875+0 records out
Aug 109:58:03localhost disktest[11048]:601600000 bytes602M574MBcopie 327263s,
1.8 GB/s
Aug 109:58:03localhost disktest[11048]:
Aug 109:58:03localhost disktest[11048]:Testingblocksize=8k
Aug 109:58:03localhost disktest[11048]: 73437+1 recordsin
Aug 109:58:03localhost disktest[11048]: 73437+1 records out
Aug 109:58:03localhost disktest[11048]:601600000 bytes(602MB574 MiBcopie 299182s,
2.0 GB/s
Aug109:58:03localhost disktest[11048]:
Aug 109:58:03localhost disktest[11048] Testingblocksize=16k
Aug 109:58:04 localhost disktest[11048]:36718+1 recordsin
Aug 109:58:04 localhost disktest[11048]:36718+1 records out
Aug 109:58:04localhost disktest[11048]:601600000 bytes(602MB574MB)copied 282859s,
2.1 GB/s


这是⼀个简单却强⼤的技巧,相信你在未来的⼯作和学习中会发现其巨⼤的价值。




Linux⽤⼾注意!这个技巧让你的脚本输出永不丢失的评论 (共 条)

分享到微博请遵守国家法律