其余的答案都非常好,但只是想添加一些额外的信息,以防有人来这里寻找替代/更新多线回声的解决方案。
所以我想和大家分享一个例子。在CentOS系统上尝试了以下脚本,并使用“timedatectl”命令,该命令基本上打印了系统的一些详细时间信息。
我决定使用这个命令,因为它的输出包含多行和完全适用于下面的例子:
#!/bin/bash
while true; do
COMMAND=$(timedatectl) #Save command result in a var.
echo "$COMMAND" #Print command result, including new lines.
sleep 3 #Keep above's output on screen during 3 seconds before clearing it
#Following code clears previously printed lines
LINES=$(echo "$COMMAND" | wc -l) #Calculate number of lines for the output previously printed
for ((i=1; i <= $(($LINES)); i++));do #For each line printed as a result of "timedatectl"
tput cuu1 #Move cursor up by one line
tput el #Clear the line
done
done
以上将打印的结果“timedatectl
”永远将取代之前的回声更新结果。
我不得不提的是,这段代码只是一个例子,但根据您的需要,可能不是最好的解决方案。 类似的命令几乎相同(至少在视觉上)是“watch -n 3 timedatectl
”。
但这是一个不同的故事。 :)
希望帮助!
只是对未来的一个提示:printf会做同样的事情,没有任何选项。优点是printf在每个环境和操作系统中的行为通常都是相似的,而echo有时表现得非常不同。对于跨平台脚本(或者如果你认为你可能会关心这一点),使用printf是最佳实践。 –
真棒@WilliamTFroggard谢谢你的朋友。 –
'printf a; printf b'输出'ab' ---'printf a \\ r; printf b'输出'b' ---'printf a \\ r;睡1; printf b''输出'a',然后'b' – XavierStuvw