1 unix
我正在尝试更改终端中回显行的文本,而 \r 对我有用,但当我将其放入 .sh 文件时则不然。我想运行一个 .sh 文件以 1 秒的时间间隔更改回显行(不要问为什么)。当我做
echo -ne 'hello\r'
sleep 1
echo -ne 'bye\r'
Run Code Online (Sandbox Code Playgroud)
它输出
-ne hello
-ne bye
Run Code Online (Sandbox Code Playgroud)
我如何实现我的目标?
重要部分:
- 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)
所以像:
echo -ne "\033[50D"
echo -ne "\033[K"
Run Code Online (Sandbox Code Playgroud)
使用printf
,这是标准化的,而不是 的-ne
选项echo
,哪些不是。
printf '\033[K%s\r' "hello world"
sleep 1
printf '\033[K%s\r' "bye now"
Run Code Online (Sandbox Code Playgroud)
确保在退出时打印换行符,例如
trap 'echo' 0
Run Code Online (Sandbox Code Playgroud)
在第一个 printf 命令之前。