文章目录
- 一、写在哪个文件生效?(关键)
-
- [✅ Bash 环境下生效位置(最常见)](#✅ Bash 环境下生效位置(最常见))
-
- [1️⃣ 全局生效(所有用户)](#1️⃣ 全局生效(所有用户))
- [✅ 推荐方式(最规范)](#✅ 推荐方式(最规范))
- [2️⃣ 全局兜底(老系统)](#2️⃣ 全局兜底(老系统))
- [3️⃣ 当前用户生效](#3️⃣ 当前用户生效)
- [✅ 各文件加载顺序(很重要)](#✅ 各文件加载顺序(很重要))
- 二、不同场景推荐配置位置
- 三、验证是否生效
- 四、一句话总结(运维必记)
一、写在哪个文件生效?(关键)
✅ Bash 环境下生效位置(最常见)
1️⃣ 全局生效(所有用户)
✅ 推荐方式(最规范)
bash
/etc/profile.d/history_optimize.sh
内容示例:
bash
cat >> /etc/profile.d/history_optimize.sh << EOF
#当前 shell 会话中保存的命令条数
export HISTSIZE=10000
#历史文件中最多保存多少条命令
export HISTFILESIZE=50000
#时间戳(审计必备)
export HISTTIMEFORMAT="%F %T "
#空格开通连续重复不记录:整段历史中去重
export HISTCONTROL=ignoreboth:erasedups
#忽略指定命令
export HISTIGNORE="history*:exit:pwd:clear"
#启用追加模式(⭐多窗口必备),防止多终端 history 互相覆盖
shopt -s histappend
#实时写入历史
PROMPT_COMMAND='history -a'
EOF
chmod +x /etc/profile.d/history_optimize.sh
source /etc/profile.d/history_optimize.sh
📌 优点:
- 系统级
- 自动加载
- 不影响用户自定义配置
2️⃣ 全局兜底(老系统)
bash
/etc/profile
⚠️ 不推荐大量修改,容易被系统升级覆盖
3️⃣ 当前用户生效
bash
~/.bashrc
或:
bash
~/.bash_profile
📌 适用于:
- 个人运维账号
- 跳板机用户
✅ 各文件加载顺序(很重要)
text
登录 shell:
/etc/profile
↓
/etc/profile.d/*.sh
↓
~/.bash_profile
↓
~/.bashrc
📌 结论:
- 登录服务器 → 看
/etc/profile.d/ - 非登录 shell(SSH 再 su) → 看
~/.bashrc
二、不同场景推荐配置位置
| 场景 | 推荐文件 |
|---|---|
| 生产服务器所有用户 | /etc/profile.d/history_optimize.sh |
| 个人运维账号 | ~/.bashrc |
| 跳板机 | /etc/profile.d/ |
| 容器基础镜像 | /etc/profile.d/ |
三、验证是否生效
bash
echo $HISTSIZE
echo $HISTFILESIZE
echo $HISTTIMEFORMAT
shopt histappend
查看历史:
bash
history | head
四、一句话总结(运维必记)
history 优化配置 = 数量 + 时间 + 去重 + 实时写入 + 正确文件