如何在此特定的ping命令上打印错误消息?

时间:2018-09-19 12:09:43

标签: linux termux

ping 8.8.8.8 | while read pong; do echo "$(date +%F_%T) - - $pong"; done >> file.txt

当互联网掉线时,它仅在终端(termux android)中显示“目的地不可达”,而在文本文件中则不显示。我也希望在文本文件中显示错误消息。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用&>将stdout和stderr都重定向到输出文件。

例如:

$ ping <IPaddr> | while read pong; do echo "$(date +%F_%T) - - $pong"; done >> file.txt 2>&1

[root@localhost tmp]#  ping 192.168.56.149 | while read pong; do echo "$(date +%F_%T) - - $pong"; done > file.txt 2>&1
^C
[root@localhost tmp]# cat file.txt
2018-09-18_18:03:28 - - PING 192.168.56.149 (192.168.56.149) 56(84) bytes of data.
2018-09-18_18:03:28 - - From 192.168.56.102 icmp_seq=1 Destination Host Unreachable
2018-09-18_18:03:28 - - From 192.168.56.102 icmp_seq=2 Destination Host Unreachable
2018-09-18_18:03:28 - - From 192.168.56.102 icmp_seq=3 Destination Host Unreachable
[root@localhost tmp]#