使用 echo 更新终端中的多行
Update multiple line in terminal with echo
我有一个项目要完成,但我有点误解了这个主题。
Objectiv
- 在终端上打印几行。
- 实时更新数值。
作为测试,我尝试了从命令 ps
模拟的 10 行,持续 30 秒。
`
#!/bin/bash
test=$(ps -ao pid,pcpu,time,comm | head -n10)
for time in $(seq 1 30); do
echo -ne "$test\r"
sleep 1
test=$(ps -ao pid,pcpu,time,comm | head -n10)
done
- 我知道我的代码不干净,我正在努力学习,所以我访问了 console_codes 的手册页,我知道你必须使用类似
echo -e " text area 3\r"
或类似的东西以获得正确的光标位置以更新行,我对一行没问题,但是对于十行我完全迷路了。
- 我在一个
echo
上使用了一个变量来刷新,但我发现我对这个问题的看法是错误的。
- 如果可能的话,我想要我的示例的解决方案以及关于如何处理多行的解释,因为我的示例打印在新行上而不是 update/erase 旧行。
注意:该示例不是我的作业,但它代表了我现在面临的挑战
感谢您的宝贵时间。
最简单、最便携和最稳定的解决方案是在每次迭代时清除屏幕:
#!/bin/bash
for i in {1..30} ; do
clear
# Print several lines
printf "foo %d\n" "${i}"
printf "bar %d\n" "${i}"
sleep 1
done
或者您可以使用以下序列:
# Save the cursor position
printf "3[s"
# Print two empty dummy lines
printf "\n\n"
for i in {1..30} ; do
# Delete the last two lines
printf "3[2K"
# Restore the cursor position
printf "3[u"
# Print two lines
printf "foo ${i}\n"
printf "bar ${i}\n"
sleep 1
done
请注意,上述 ^^^ 解决方案只有在您事先知道要打印/清除的行数时才有效。
可以用echo -e "\e[nA"
排n行(n
应该是整数)。如果所有行的长度相同,则执行以下操作。
lines=10
for i in {0..30}; do
ps -ao pid,pcpu,time,comm | head -n${lines} # print `$lines` lines
sleep 1
echo -e "\e[$((${lines}+1))A" # go `$lines + 1` up
done
我有一个项目要完成,但我有点误解了这个主题。
Objectiv
- 在终端上打印几行。
- 实时更新数值。
作为测试,我尝试了从命令 ps
模拟的 10 行,持续 30 秒。
`
#!/bin/bash
test=$(ps -ao pid,pcpu,time,comm | head -n10)
for time in $(seq 1 30); do
echo -ne "$test\r"
sleep 1
test=$(ps -ao pid,pcpu,time,comm | head -n10)
done
- 我知道我的代码不干净,我正在努力学习,所以我访问了 console_codes 的手册页,我知道你必须使用类似
echo -e " text area 3\r"
或类似的东西以获得正确的光标位置以更新行,我对一行没问题,但是对于十行我完全迷路了。 - 我在一个
echo
上使用了一个变量来刷新,但我发现我对这个问题的看法是错误的。 - 如果可能的话,我想要我的示例的解决方案以及关于如何处理多行的解释,因为我的示例打印在新行上而不是 update/erase 旧行。
注意:该示例不是我的作业,但它代表了我现在面临的挑战
感谢您的宝贵时间。
最简单、最便携和最稳定的解决方案是在每次迭代时清除屏幕:
#!/bin/bash
for i in {1..30} ; do
clear
# Print several lines
printf "foo %d\n" "${i}"
printf "bar %d\n" "${i}"
sleep 1
done
或者您可以使用以下序列:
# Save the cursor position
printf "3[s"
# Print two empty dummy lines
printf "\n\n"
for i in {1..30} ; do
# Delete the last two lines
printf "3[2K"
# Restore the cursor position
printf "3[u"
# Print two lines
printf "foo ${i}\n"
printf "bar ${i}\n"
sleep 1
done
请注意,上述 ^^^ 解决方案只有在您事先知道要打印/清除的行数时才有效。
可以用echo -e "\e[nA"
排n行(n
应该是整数)。如果所有行的长度相同,则执行以下操作。
lines=10
for i in {0..30}; do
ps -ao pid,pcpu,time,comm | head -n${lines} # print `$lines` lines
sleep 1
echo -e "\e[$((${lines}+1))A" # go `$lines + 1` up
done