在以下命令中,我在alert.txt中获取顶部输出的特殊字符。如何防止它....
#!/bin/sh
topsnapshot=`top -n 5`
echo -e "\n\n===========================TOP COMMAND SNAPSHOT====================================================" > /tmp/alert.txt
echo "$topsnapshot" >> /tmp/alert.txt
输出:
===========================TOP COMMAND SNAPSHOT====================================================
^[[H^[[2J^[(B^[[mtop - 18:56:01 up 112 days, 18:22, 5 users, load average: 0.99, 0.73, 0.33^[(B^[[m^[[39;49m^[[K
Tasks:^[(B^[[m^[[39;49m^[(B^[[m 142 ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m 2 ^[(B^[[m^[[39;49mrunning,^[(B^[[m^[[39;49m^[(B^[[m 139 ^[(B^[[m^[[39;49msleeping,^[(B^[[m^[[39;49m^[(B^[[m 0 ^[(B^[[m^[[39;49mstopped,^[(B^[[m^[[39;49m^[(B^[[m 1 ^[(B^[[m^[[39;49mzombie^[(B^[[m^[[39;49m^[[K
Cpu(s):^[(B^[[m^[[39;49m^[(B^[[m 0.2%^[(B^[[m^[[39;49mus,^[(B^[[m^[[39;49m^[(B^[[m 0.2%^[(B^[[m^[[39;49msy,^[(B^[[m^[[39;49m^[(B^[[m 0.0%^[(B^[[m^[[39;49mni,^[(B^[[m^[[39;49m^[(B^[[m 99.1%^[(B^[[m^[[39;49mid,^[(B^[[m^[[39;49m^[(B^[[m 0.4%^[(B^[[m^[[39;49mwa,^[(B^[[m^[[39;49m^[(B^[[m 0.0%^[(B^[[m^[[39;49mhi,^[(B^[[m^[[39;49m^[(B^[[m 0.0%^[(B^[[m^[[39;49msi,^[(B^[[m^[[39;49m^[(B^[[m 0.0%^[(B^[[m^[[39;49mst^[(B^[[m^[[39;49m^[[K
Mem: ^[(B^[[m^[[39;49m^[(B^[[m 4142428k ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m 2291280k ^[(B^[[m^[[39;49mused,^[(B^[[m^[[39;49m^[(B^[[m 1851148k ^[(B^[[m^[[39;49mfree,^[(B^[[m^[[39;49m^[(B^[[m 569928k ^[(B^[[m^[[39;49mbuffers^[(B^[[m^[[39;49m^[[K
Swap:^[(B^[[m^[[39;49m^[(B^[[m 5668856k ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m 76k ^[(B^[[m^[[39;49mused,^[(B^[[m^[[39;49m^[(B^[[m 5668780k ^[(B^[[m^[[39;49mfree,^[(B^[[m^[[39;49m^[(B^[[m 1088948k ^[(B^[[m^[[39;49mcached^[(B^[[m^[[39;49m^[[K
^[[6;1H
^[[7m PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND ^[(B^[[m^[[39;49m^[[K
^[(B^[[m^[(B^[[m31832 root 25 0 6072 2100 1228 R 99.2 0.1 6:40.14 t.py ^[(B^[[m^[[39;49m
^[(B^[[m 1 root 15 0 2160 644 556 S 0.0 0.0 0:17.83 init
答案 0 :(得分:2)
尝试:
topsnapshot=`top -b -n 5`
答案 1 :(得分:1)
这适用于Linux:
topsnapshot=$(TERM=dumb top -n 5)
哑终端没有逃脱序列。
答案 2 :(得分:0)
您在评论中声明了其他答案,您不希望它重复5次,但在您的示例命令中,您使用-n 5
。 -n 5
告诉top
重复5次。因此,请尝试以下操作,使其仅重复一次:
topsnapshot=$(top -b -n 1)
如果您只想要前几行输出,请使用head
:
topsnapshot=$(top -b -n 1 | head -n 25)
要打印捕获的输出,我建议如下:
printf '%s\n' "${topsnapshot}"
请务必记住${topsnapshot}
周围的双引号。我不使用echo
,因为它may or may not treat backslashes specially取决于shell的实现。