Bash Prompt HOWTO:
Prev Chapter 6. ANSI Escape Sequences: Colours and Cursor Movement Next
- 6.2. Cursor Movement
ANSI escape sequences allow you to move the cursor around the screen at will. This is more useful for full screen user interfaces generated by shell scripts, but can also be used in prompts. The movement escape sequences are as follows:
\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
The latter two codes are NOT honoured by many terminal emulators. The only ones that I’m aware of that do are xterm and nxterm - even though the majority of terminal emulators are based on xterm code. As far as I can tell, rxvt, kvt, xiterm, and Eterm do not support them. They are supported on the console.
Try putting in the following line of code at the prompt (it’s a little clearer what it does if the prompt is several lines down the terminal when you put this in): echo -en “\033[7A\033[1;35m BASH \033[7B\033[6D” This should move the cursor seven lines up screen, print the word ” BASH “, and then return to where it started to produce a normal prompt. This isn’t a prompt: it’s just a demonstration of moving the cursor on screen, using colour to emphasize what has been done.
Save this in a file called “clock”:
!/bin/bash
function prompt_command {
let prompt_x=$COLUMNS-5
}
PROMPT_COMMAND=prompt_command
function clock {
local BLUE="\[\033[0;34m\]"
local RED="\[\033[0;31m\]"
local LIGHT_RED="\[\033[1;31m\]"
local WHITE="\[\033[1;37m\]"
local NO_COLOUR="\[\033[0m\]"
case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esac
PS1="${TITLEBAR}\
\[\033[s\033[1;\$(echo -n \${prompt_x})H\]\
$BLUE[$LIGHT_RED\$(date +%H%M)$BLUE]\[\033[u\033[1A\]
$BLUE[$LIGHT_RED\u@\h:\w$BLUE]\
$WHITE\$$NO_COLOUR "
PS2='> '
PS4='+ '
}
This prompt is fairly plain, except that it keeps a 24 hour clock in the upper right corner of the terminal (even if the terminal is resized). This will NOT work on the terminal emulators that I mentioned that don’t accept the save and restore cursor position codes. If you try to run this prompt in any of those terminal emulators, the clock will appear correctly, but the prompt will be trapped on the second line of the terminal.
这篇博客介绍了如何在Bash脚本中利用ANSI转义序列进行终端控制,特别是关于光标的移动。尽管一些终端模拟器如rxvt和Eterm不支持某些代码,但xterm和nxterm可以。示例代码演示了如何移动光标并在屏幕上显示彩色文本。此外,还提供了一个名为'clock'的脚本示例,它在终端右上角显示24小时制的时钟,但不适用于不支持保存和恢复光标位置代码的终端模拟器。
3749

被折叠的 条评论
为什么被折叠?



