在bash循环脚本中,如何刷新同一行的输出?(取最后输出的位置)



例如,我每秒都有像一样的输出

user@pc:
A
B
C
D
E

我希望在同一行中从A到E的输出刷新(没有创建新行)

谢谢!

您可以使用carriage return字符"r"。检查以下两者之间的差异:

for x in $(seq 10); do printf "$x"; sleep 1; done

for x in $(seq 10); do printf "$xr"; sleep 1; done

取决于您的输入来自哪里

我会采用以下技巧。

对于文件:

#!/bin/bash
while read line
do
echo -e "e[1A" # moving the cursor back to the previously printed line
sleep 1s;
echo -ne "$linee[K" # e[K cleans the residues of the previous output.
done <file_name
echo

对于阵列:

#!/bin/bash
arr=(12 11 10 9 8 7 6 5 4 3 2 1 0)
for i in ${arr[@]}
do
echo -e "e[1A"
sleep 1s;
echo -ne "Waiting time : "$i" Secondse[K"
done
echo

最新更新