注本文为 “Linux 命令与服务器安全加固” 相关合辑。英文引文机翻未校。中文引文略作重排。如有内容异常请看原文。How to Prevent Passwords from Saving in Bash History如何防止密码被保存到 Bash 历史记录中Ravi SaiveLast Updated: April 30, 2026Every Linux user eventually runs a command they’d rather not preserve – a curl with a hardcoded password, an export with an API key, or a one-liner that would confuse any sysadmin who read it three months later. Knowing how to control what ends up in your bash history is as much a security habit as locking down SSH*.每个 Linux 用户迟早都会执行一条不想被保留的命令——比如带硬编码密码的 curl 命令、含 API 密钥的 export 命令或是一条三个月后让系统管理员一头雾水的单行指令。学会控制 bash 历史记录的内容是和加固 SSH 同等重要的安全习惯。You’ve probably been there: you paste a command with a password embedded, hitEnter, and immediately wonder how many places that string just landed. Bash stores every command you type in~/.bash_historyby default, and on most systems, that file is readable by anyone who can access your account. And if you’re sharing a server with other admins, that history file is the first place anyone looks when something breaks.你大概率遇到过这种情况粘贴一条带密码的命令按下回车后立刻担心这条敏感字符串会被记录到哪里。Bash 默认会把你输入的所有命令保存到~/.bash_history在大多数系统中任何能访问你账户的人都可以读取该文件。如果你和其他管理员共用一台服务器出问题时历史记录文件会是第一个被检查的地方。The good news is thatBashgives you precise control over what it saves, when it saves it, and how to scrub individual entries.好消息是Bash可以让你精确控制保存哪些内容、何时保存以及如何清除单条记录。How Bash Stores Command in HistoryBash 如何存储命令历史Before you can control history, you need to understand whenBashwrites it. For example, during a session, every command goes into an in-memory history list first.在控制历史记录之前你需要了解Bash何时写入记录。例如在一个会话期间所有命令会先存入内存中的历史列表。When the session ends cleanly, that list gets appended to~/.bash_historyon disk, which matters because if your terminal crashes or you close it with kill, nothing from that session gets saved.当会话正常结束时该列表会追加到磁盘上的~/.bash_history文件中。这一点很重要因为如果终端崩溃或用 kill 命令关闭本次会话的所有内容都不会被保存。The key variables that govern this behavior live in your shell environment, and you can check them right now:控制该行为的关键变量位于你的 shell 环境中你可以立即查看echo$HISTFILEecho$HISTSIZEecho$HISTFILESIZEOutput:输出/home/ravi/.bash_history 1000 2000Let me explain the command output:我来解释一下命令输出HISTFILEis where history gets written on exit.HISTFILE会话退出时历史记录写入的文件路径。HISTSIZEcontrols how many commands the in-memory list holds per session.HISTSIZE每个会话在内存中可保存的命令数量。HISTFILESIZEcontrols how many lines the history file can grow to on disk.HISTFILESIZE磁盘上历史记录文件的最大行数。Most distros default to1000in-memory and2000on disk, so your file keeps the last2000commands across all previous sessions. Understanding that gap between “in memory” and “written to disk” is what makes the next few techniques work cleanly.大多数发行版默认内存保存1000条、磁盘保存2000条因此文件会保留所有之前会话的最近2000条命令。理解内存与磁盘写入之间的区别是让后续技巧干净生效的关键。How to Prevent a Command from Being Saved in Bash History如何防止单条命令被保存到 Bash 历史记录The easiest way to stop Bash from saving a command in your history is surprisingly simple, just add a space before the command.阻止 Bash 保存单条命令最简单的方法出奇地简单在命令前加一个空格。For example, when you type a command like this, it gets saved in your history.例如输入这样的命令会被保存到历史记录export API_KEYsupersecretkey123But if you add one space at the beginning:但如果在开头加一个空格export API_KEYsupersecretkey123Bash won’t record this line at all, as long asHISTCONTROLincludesignorespace.只要HISTCONTROL包含ignorespaceBash 就完全不会记录这一行。So, firt check whether it’s already set:首先检查它是否已设置echo $HISTCONTROLOutput:输出ignoredups:ignorespaceIf you seeignorespaceorignorebothin the output, you’re already covered.如果输出中包含ignorespace或ignoreboth说明已生效。If the variable is empty or missing, add this to your~/.bashrc:如果该变量为空或不存在将以下内容添加到~/.bashrcexport HISTCONTROLignorespaceThen reload it:然后重新加载配置source ~/.bashrcDelete a Specific Command from Bash History从 Bash 历史记录中删除单条命令The leading-space trick only works before you run a command, but if you already ran something and want it gone, use history-dwith the line number:开头加空格的技巧仅在执行命令前有效。如果已经执行并想删除可使用history -d加行号For example, first, list your bash history.例如先列出 bash 历史记录historyOutput:输出497 sudo systemctl restart nginx 498 export DB_PASShunter2 499 curl https://api.example.com/token 500 ls -la /etc/nginxTo delete line 498:删除第 498 行history -d 498Output:输出497 sudo systemctl restart nginx 499 curl https://api.example.com/token 500 ls -la /etc/nginxThe entry is gone from the in-memory list, but you’re not done yet. That deletion only lives in memory until the session ends. When Bash writes history to disk on exit, the gap closes, and your~/.bash_historyfile won’t have the entry either, as long as you don’t runhistory -amanually before closing the terminal.该条目已从内存列表中删除但操作还未完成。删除效果仅保留在内存中直到会话结束。只要关闭终端前不手动执行history -aBash 在退出写入磁盘时~/.bash_history中也不会有该条目。If you want to scrub the on-disk file immediately without waiting for the session end, runhistory -wafter the deletion:如果不想等待会话结束想立即清除磁盘文件删除后执行history -wThis writes the current in-memory list (without the deleted entry) directly to~/.bash_history, overwriting whatever was there before.这会将当前内存列表不含已删条目直接写入~/.bash_history覆盖原有内容。Ignore Duplicate Commands in Bash History在 Bash 历史记录中忽略重复命令Repeated commands like ls, cd, clear, or git status fill up history fast and make it harder to find the commands you actually care about.重复的命令如 ls、cd、clear 或 git status 会快速填满历史记录让你更难找到真正需要的命令。SetHISTCONTROLtoignoredupsand Bash will skip any command that matches the one immediately before it:将HISTCONTROL设置为ignoredupsBash 会跳过与上一条完全相同的命令export HISTCONTROLignoredupsTo combine both behaviors – ignore leading spaces and duplicates – useignoreboth:如果要同时生效——忽略开头空格和重复命令——使用ignorebothexport HISTCONTROLignorebothAdd this to your~/.bashrcso it persists across sessions:将其添加到~/.bashrc让配置在所有会话中永久生效echoexport HISTCONTROLignoreboth~/.bashrcsource~/.bashrcStop Saving Certain Commands in Bash History禁止保存特定类型的命令到 Bash 历史记录TheHISTCONTROLhandles the space-prefix trick and duplicates, butHISTIGNORElets you define specific patterns that Bash always skips. Any command matching a pattern here never enters the history list at all:HISTCONTROL处理空格前缀和重复命令而HISTIGNORE可让你定义 Bash 永久忽略的命令模式。匹配这些模式的命令根本不会进入历史列表export HISTIGNOREls:ls -la:cd:pwd:clear:history:exitEach pattern is separated by a colon. You can use glob-style wildcards too, soexport *would suppress every export command:每个模式用冒号分隔。你也可以使用通配符例如export *会屏蔽所有 export 命令export HISTIGNOREls*:cd*:pwd:clear:history:export *:curl *token*Add it to~/.bashrcto make it permanent, and source the file again. Be careful not to make the patterns too broad; if you ignoresudo *, you’ll lose the audit trail for every privileged command you’ve ever run, which creates a different kind of problem.添加到~/.bashrc使其永久生效并重新加载文件。注意不要把模式设置得太宽泛如果忽略sudo *你会丢失所有特权命令的审计轨迹这会带来另一类问题。Turn Off Command History Temporarily临时关闭命令历史记录Sometimes you want to work on a server without leaving any trace at all such as setting up credentials, auditing a config, or doing incident response on a shared box.有时你需要在服务器上不留任何痕迹地操作例如配置凭证、审计配置或在共享服务器上处理应急响应。SetHISTFILEto/dev/nullfor the current session:将当前会话的HISTFILE设置为/dev/nullexport HISTFILE/dev/nullFrom that point forward in the session, nothing gets written to disk. The in-memory list still builds up (so you can use the up arrow), but when the session ends, the in-memory list evaporates instead of being flushed to a file.从此时起本次会话的所有内容都不会写入磁盘。内存列表仍会累积因此你可以用向上箭头翻查但会话结束时内存列表会直接消失不会写入文件。You can also combine this withunset HISTFILEif you want to be explicit, but pointing to/dev/nullis the more portable approach and works the same way on every distro.如果你想更明确也可以配合unset HISTFILE使用但指向/dev/null是更通用的方法在所有发行版上效果一致。How to Clear the Entire History File清空整个历史记录文件To start clean, delete the full history file and remove all past commands.想从头开始清空历史文件并删除所有过往命令history -c history -whistory -cclears the in-memory history list for the current session.history -c清空当前会话的内存历史列表。history -wthen writes that empty list to~/.bash_history, overwriting the file.history -w将空列表写入~/.bash_history覆盖文件。After running this,cat ~/.bash_historyreturns nothing. Theoperator means the second command only runs if the first succeeds, so you won’t accidentally clear the file mid-session if something goes wrong.执行后cat ~/.bash_history会返回空内容。表示第一条命令成功后才执行第二条避免出错时意外清空文件。Conclusion总结You now have 5 distinct ways to control bash history: the leading-space trick for one-off sensitive commands,history -dfor post-run cleanup,HISTCONTROLfor ignoring duplicates and spaces globally,HISTIGNOREfor permanent pattern-based exclusions, andHISTFILE/dev/nullfor session-wide suppression.现在你掌握了 5 种控制 Bash 历史记录的方法针对单次敏感命令的开头空格技巧、执行后清理的history -d、全局忽略重复与空格的HISTCONTROL、永久按模式屏蔽的HISTIGNORE以及全会话禁用的HISTFILE/dev/null。Start with addingexport HISTCONTROLignorebothto your~/.bashrcright now. Then think about what patterns belong in yourHISTIGNORE.现在就把export HISTCONTROLignoreboth添加到~/.bashrc然后思考哪些命令模式应该加入HISTIGNORE。If you’re regularly exporting tokens or running curl with auth headers, those belong there. It takes 5 minutes and saves you from cleaning up sensitive data later.如果你经常导出令牌或执行带认证头的 curl 命令这些都应该加入屏蔽列表。只需 5 分钟就能避免后续清理敏感数据的麻烦。Linux 防止密码泄露Bash 历史记录安全管控 SSH 加固Linux 终端.bashrc安全配置与服务器安全加固临时操作 → 单次规避 → 进阶操作 → 全局永久防护 → 事后补救 → SSH 服务器加固一、Bash 历史记录防密码泄露操作针对密码、API 密钥、令牌等敏感命令提供三种层级的事前规避方案按需选用避免敏感信息被记录。1.1 单次命令前加空格通法Linux 原生自带的轻量机制无需修改配置仅需命令开头加1 个空格命令不会写入历史记录。前置条件校验该功能依赖HISTCONTROL变量绝大多数系统默认开启执行命令校验echo$HISTCONTROL正常输出ignoredups:ignorespace/ignoreboth代表已生效。实操对比# 不安全无空格命令会被写入历史记录exportDB_PASSadmin123456curlhttps://api.test.com/token-uuser:pass# 安全开头加空格完全不记录exportDB_PASSadmin123456curlhttps://api.test.com/token-uuser:pass未开启修复永久生效若输出为空手动开启空格忽略规则echoexport HISTCONTROLignorespace~/.bashrcsource~/.bashrc1.2 会话临时关闭全局历史记录适用于批量敏感操作、应急运维、共享服务器操作可关闭当前终端会话所有历史写入实现全程零留存。原理Bash 默认将命令写入~/.bash_history磁盘文件修改HISTFILE指向空设备可终止磁盘写入内存仅临时缓存支持上下箭头翻查会话关闭后记录自动销毁。实操命令# 临时关闭当前会话所有历史记录写入exportHISTFILE/dev/null补充说明仅对当前终端会话生效重启终端自动恢复默认兼容所有 Linux 发行版通用性极强等效命令unset HISTFILE前者兼容性更优。1.3 进阶fc 命令批量编辑敏感指令fcfix command为 Bash 内置命令无需修改配置支持批量编写、执行敏感命令适合复杂多指令敏感操作场景。基础用法执行fc打开系统默认编辑器nano/vim编写多条敏感命令保存退出后自动执行无任何历史记录留存。# 打开编辑器编写敏感指令fc编辑器内示例内容exportAPI_KEYtest_secret_789curl-XPOST https://api.test.com/login-Htoken:xxx进阶修改历史命令# 编辑并执行上一条命令fc-1# 编辑指定行号的历史命令先 history 查行号fc500功能特点支持批量编写多条敏感命令一次性执行无需清空历史、无需修改环境变量零副作用系统原生内置无需额外安装依赖。二、Bash 历史记录全局永久安全管控通过环境变量永久优化历史记录规则自动过滤重复、敏感命令规范记录大小从根源减少泄露风险适配所有终端会话。2.1 环境变量参数说明# 查看历史文件存储路径echo$HISTFILE# 查看单会话内存最大保存命令数echo$HISTSIZE# 查看磁盘历史文件最大总行数echo$HISTFILESIZE2.2 自动忽略重复命令# 仅忽略连续重复命令echoexport HISTCONTROLignoredups~/.bashrc# 同时忽略空格前缀命令 连续重复命令echoexport HISTCONTROLignoreboth~/.bashrcsource~/.bashrc2.3 永久屏蔽指定敏感命令HISTIGNORE自定义黑名单匹配规则的命令直接不进入历史记录适配日常敏感操作场景。echoexport HISTIGNOREls*:cd*:pwd:clear:history:export *:curl *token*:* -u *~/.bashrcsource~/.bashrc规则说明自动屏蔽目录操作、清空命令、密钥导出、带密码 curl 请求等敏感指令。2.4 自定义历史记录存储大小# 单会话内存保存 1000 条磁盘文件最大 2000 条系统默认参数exportHISTSIZE1000exportHISTFILESIZE2000三、历史记录泄露事后清理方案针对已执行的敏感命令精准删除、全局清空两种补救方式快速消除泄露隐患。3.1 删除单条敏感记录# 1. 查看历史获取敏感命令行号history# 2. 删除指定行示例删除第 498 行history-d498# 3. 立即同步至磁盘彻底清除history-w3.2 清空全部历史记录# 清空内存记录 覆盖磁盘文件清空所有历史记录history-chistory-w四、SSH 服务器安全加固终端历史记录防泄露为前置防护SSH 加固可提升服务器安全能力降低密码、密钥泄露引发的入侵风险。4.1 安全配置项# 编辑 SSH 配置文件sudovim/etc/ssh/sshd_config写入以下安全配置直接全覆盖# 禁止 root 超级用户远程登录 PermitRootLogin no # 关闭密码登录仅允许密钥登录 PasswordAuthentication no ChallengeResponseAuthentication no # 自定义允许登录的普通用户名替换为自己的用户名 AllowUsers 自定义用户名 # 可选修改默认 22 端口1024-65535规避暴力扫描 Port 22224.2 重启服务生效sudosystemctl restart sshd4.3 密钥登录替代密码# 生成 ed25519 密钥RSA 之外的可选密钥类型ssh-keygen-ted25519# 将公钥推送至远程服务器实现免密登录ssh-copy-id 用户名服务器IP五、安全配置脚本部署所有 Bash 历史记录安全配置执行后永久生效无需逐条手动配置。#!/bin/bash# Bash 历史记录安全加固一键脚本echo # 同时忽略空格前缀、重复命令 export HISTCONTROLignoreboth # 屏蔽日常敏感、冗余命令 export HISTIGNOREls*:cd*:pwd:clear:history:export *:curl *token*:* -u * # 规范历史记录存储大小 export HISTSIZE1000 export HISTFILESIZE2000 ~/.bashrc# 重载配置立即生效source~/.bashrcechoBash 历史记录安全配置部署完成六、总结单次操作命令前加空格适配临时单条敏感指令场景全会话export HISTFILE/dev/null临时关闭所有历史写入批量操作fc命令编辑执行指令无记录留存全局永久防护HISTCONTROLHISTIGNORE自动过滤冗余、敏感记录事后补救清理history -d精准删记录history -c全局清空服务器安全防护SSH 禁用密码/root 登录密钥登录可抵御暴力破解。referenceHow to Keep Passwords Out of Bash History on Linuxhttps://www.tecmint.com/hide-commands-bash-history-linux/…