以 root 登錄 Linux 後,提示符顯示為 -bash-3.2# 而非預期的 [root@hostname ~]#,且 ls 無色彩、ll 別名失效。原因是用戶家目錄缺少 Shell 初始化文件(.bashrc、.bash_profile)。一鍵修復。
-bash-3.2# ls
# 無色彩、無別名、提示符簡陋
-m 參數,未複製 /etc/skel/ 模板文件# 複製骨架文件到家目錄
cp /etc/skel/.{bash_profile,bashrc} ~
# 立即生效
source ~/.bashrc
[root@hostname ~]# ls --color=auto
# 提示符恢復、別名生效、色彩顯示正常
| 文件 | 讀取時機 | 典型內容 |
|---|---|---|
.bash_profile | 登錄 Shell(SSH、控制台登錄) | 環境變量、PATH、啟動程序 |
.bashrc | 交互式非登錄 Shell(終端標籤頁、腳本調用 bash) | 別名、函數、提示符 PS1、歷史設置 |
.profile | 登錄 Shell(Bash 無 .bash_profile 時回退) | 同 .bash_profile |
# .bash_profile 中 source .bashrc,統一配置入口
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
.bashrc.bash_profile 僅負責環境變量與調用 .bashrc/etc/profile、/etc/bashrc#!/bin/bash
# fix_bash_prompt.sh - 為所有缺失配置的用戶修復提示符
for user_home in /home/* /root; do
[ -d "$user_home" ] || continue
user=$(basename "$user_home")
if [ ! -f "$user_home/.bashrc" ] || [ ! -f "$user_home/.bash_profile" ]; then
cp /etc/skel/.{bash_profile,bashrc} "$user_home/"
chown "$user:$user" "$user_home/.bash_profile" "$user_home/.bashrc"
echo "Fixed: $user"
fi
done