我正在编写安装脚本,并希望显示脚本的进展状态.
例:
var1="pending"
var2="pending"
var3="pending"
print_status () {
echo "Status of Item 1 is: "$var1""
echo "Status of Item 2 is: "$var2""
echo "Status of Item 3 is: "$var3""
}
code that does something and then refreshes the
output above as the status of each variable changes.
Run Code Online (Sandbox Code Playgroud)
Ale*_*-A. 24
这段代码应该给你一个想法:
while :; do
echo "$RANDOM"
echo "$RANDOM"
echo "$RANDOM"
sleep 0.2
tput cuu1 # move cursor up by one line
tput el # clear the line
tput cuu1
tput el
tput cuu1
tput el
done
Run Code Online (Sandbox Code Playgroud)
用于man tput获取更多信息.要查看使用的功能列表man terminfo
我找到了现有答案中未提及的另一种解决方案。我正在为 openwrt 开发程序,tput默认情况下不可用。下面的解决方案受到Missing tput和Cursor Movement 的启发。
- Position the Cursor:
\033[<L>;<C>H
Or
\033[<L>;<C>f
puts the cursor at line L and column C.
- Move the cursor up N lines:
\033[<N>A
- Move the cursor down N lines:
\033[<N>B
- Move the cursor forward N columns:
\033[<N>C
- Move the cursor backward N columns:
\033[<N>D
- Clear the screen, move to (0,0):
\033[2J
- Erase to end of line:
\033[K
- Save cursor position:
\033[s
- Restore cursor position:
\033[u
Run Code Online (Sandbox Code Playgroud)
至于你的问题:
var1="pending"
var2="pending"
var3="pending"
print_status () {
# add \033[K to truncate this line
echo "Status of Item 1 is: "$var1"\033[K"
echo "Status of Item 2 is: "$var2"\033[K"
echo "Status of Item 3 is: "$var3"\033[K"
}
while true; do
print_status
sleep 1
printf "\033[3A" # Move cursor up by three line
done
Run Code Online (Sandbox Code Playgroud)
这并不能完全解决您的问题,但可能会有所帮助;要在执行每个命令后打印状态,请像这样修改 PS1:
PS1='$PS1 $( print_status )'
Run Code Online (Sandbox Code Playgroud)