0

在以下命令中,我在 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
4

3 回答 3

3

尝试:

topsnapshot=`top -b -n 5`
于 2012-03-29T14:29:59.870 回答
1

这适用于我在 Linux 上:

topsnapshot=$(TERM=dumb top -n 5)

哑终端没有转义序列。

于 2012-03-29T14:40:51.133 回答
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,因为它可能会或可能不会根据 shell 的实现专门处理反斜杠。

于 2012-03-29T15:13:23.037 回答