使用 PS1

PS1 是正常的系统提示,指示 bash 等待输入的命令。它理解一些转义序列并可以执行函数或程序。由于 bash 必须在显示提示后定位光标,因此需要知道如何计算提示字符串的有效长度。要指示 PS1 变量转义括号内的字符的非打印序列,请使用: \ [ 非打印序列的字符 \] 。所有的说法都适用于所有的 PS * vars。

(黑色插入符表示光标)

#everything not being an escape sequence will be literally printed
export PS1="literal sequence "  # Prompt is now:
literal sequence ▉

# \u == user \h == host \w == actual working directory
# mind the single quotes avoiding interpretation by shell
export PS1='\u@\h:\w > ' # \u == user, \h == host, \w actual working dir
looser@host:/some/path > ▉

# executing some commands within PS1
# following line will set foreground color to red, if user==root, 
# else it resets attributes to default
# $( (($EUID == 0)) &&  tput setaf 1)
# later we do reset attributes to default with
# $(  tput sgr0 )
# assuming being root:
PS1="\[$( (($EUID == 0)) &&  tput setaf 1 \]\u\[$(tput sgr0)\]@\w:\w \$ "
looser@host:/some/path > ▉  # if not root else <red>root<default>@host....