有时我在终端中看到一些命令将结果打印到stdout但在同一行.例如,wget打印如下箭头:
0[=> ]100%
0[ => ]100%
0[ => ]100%
0[ => ]100%
0[ =>]100%
Run Code Online (Sandbox Code Playgroud)
但它打印到同一行,所以看起来箭头正在移动.如何使用bash或sh在我的程序中实现相同的功能?我需要使用其他工具吗?
更新:
我知道我提到了wget,它默认出现在linux,基于GNU的unices中......是否有一种适用于BSD的通用方法?(比如OSX) - >好的,如果我使用bash而不是sh那么它的工作原理:)
cho*_*oba 17
使用特殊字符\r
.它返回到行的开头而不转到下一行.
for i in {1..10} ; do
echo -n '['
for ((j=0; j<i; j++)) ; do echo -n ' '; done
echo -n '=>'
for ((j=i; j<10; j++)) ; do echo -n ' '; done
echo -n "] $i"0% $'\r'
sleep 1
done
Run Code Online (Sandbox Code Playgroud)
fed*_*qui 12
您可以\r
为此目的使用:
例如,这将继续更新同一行中的当前时间:
while true; do echo -ne "$(date)\r"; done
Run Code Online (Sandbox Code Playgroud)
您也可以使用它ANSI/VT100 terminal escape sequences
来实现这一目标。
这是一个简短的例子。当然,您可以将printf
语句合并为一个。
#!/bin/bash
MAX=60
ARR=( $(eval echo {1..${MAX}}) )
for i in ${ARR[*]} ; do
# delete from the current position to the start of the line
printf "\e[2K"
# print '[' and place '=>' at the $i'th column
printf "[\e[%uC=>" ${i}
# place trailing ']' at the ($MAX+1-$i)'th column
printf "\e[%uC]" $((${MAX}+1-${i}))
# print trailing '100%' and move the cursor one row up
printf " 100%% \e[1A\n"
sleep 0.1
done
printf "\n"
Run Code Online (Sandbox Code Playgroud)
使用转义序列,您可以最大程度地控制终端屏幕。
您可以在[ 1 ]中找到可能的序列的概述。
[1] http://ascii-table.com/ansi-escape-sequences-vt-100.php