使用 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....