Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Bash PS1 提示符定制完全指南:變量含義、顏色設置、持久化配置

編輯:Linux 教學

PS1/PS2 變量含義

  • PS1:主提示符 (如 [user@host ~]$)
  • PS2:續行提示符 (命令未完等待輸入時,默認 >)

常用轉義序列速查

序列含義示例
\d日期 (Weekday Month Date)Mon Aug 1
\H完整主機名fc4.linux
\h短主機名 (第一個 . 前)fc4
\t24h 時間 (HH:MM:SS)14:30:05
\T12h 時間02:30:05 PM
\A24h 短時間 (HH:MM)14:30
\u當前用戶名root
\vBash 版本4.4.23
\w完整工作目錄 (~ 代表家目錄)/home/user/project
\W基礎目錄名 (最後一級)project
\#命令歷史編號1024
\$提示符字符 (root=#, 普通用戶=$)# / $

臨時修改與持久化

# 臨時 (當前 Shell 生效)
PS1='(\u@\H \d \t)\$ '

# 永久:編輯 ~/.bash_profile 或 ~/.bashrc
echo 'PS1="[\u@\h \w]\\$ "' >> ~/.bashrc
source ~/.bashrc

注意:export PS1 會讓子 Shell 繼承,導致 root 也用同樣提示符,建議**不 export**,分別在 root/用戶各自的 .bashrc 設置。

彩色提示符

格式:\[\e[F;Bm\] (F=前景 30–37, B=背景 40–47, 1=高亮/粗體)

# 綠色用戶@主機 藍色路徑 白色$
PS1='\[\e[32m\]\u@\h\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '

# 紅色 root 警示
if [ $UID -eq 0 ]; then
    PS1='\[\e[31;1m\]\u@\h\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]# '
else
    PS1='\[\e[32m\]\u@\h\[\e[0m\]:\[\e[34m\]\w\[\e[0m\]\$ '
fi

顏色代碼速查

代碼顏色代碼顏色
30/40黑37/47白
31/41紅90/100亮黑/亮灰背景
32/42綠91/101亮紅
33/43黃/棕92/102亮綠
34/44藍93/103亮黃
35/45紫/洋紅94/104亮藍
36/46青95/105亮紫
1高亮/粗體 (非顏色)0重置所有屬性

進階:Git 分支顯示、命令耗時、返回值

# 需安裝 git-prompt.sh
source /usr/share/git/completion/git-prompt.sh
PS1='\[\e[32m\]\u@\h\[\e[0m\]:\[\e[34m\]\w\[\e[33m\]$(__git_ps1 " (%s)")\[\e[0m\]\$ '

總結

PS1 定制通過轉義序列 + ANSI 顏色碼實現。建議:用戶綠色、root 紅色、路徑藍色、Git 分支黃色,配置在 ~/.bashrc 且不 export,兼顧美觀與辨識度。

Copyright © Windows教程網 All Rights Reserved