Linux 历史命令操作教程

简介

Linux 使用 history 命令记录命令历史记录并将其存储在文件 (~/.bash_history~/.zsh_history) 中。可以使用不同的方法配置和操作历史记录。

常用操作

查看所有命令

shell 复制代码
history

# 这将显示所有先前执行的命令以及行号

显示最新10条命令

shell 复制代码
history 10

搜索命令历史

shell 复制代码
history | grep "keyword"

示例:

shell 复制代码
history | grep ls

使用反向搜索(CTRL + R

  • CTRL + R 并开始输入部分命令

  • 继续按 CTRL + R 循环搜索命令

  • Enter 键执行选定的命令

执行历史记录中的命令

shell 复制代码
!<command_number>

示例:执行历史记录中第100号命令

shell 复制代码
!100

重新运行最后一个命令

shell 复制代码
!!

运行以特定单词开头的最后一个命令

shell 复制代码
!ls

清除当前会话历史记录

shell 复制代码
history -c

删除指定命令

shell 复制代码
history -d <command_number>

示例:

shell 复制代码
history -d 50

# 删除编号50的命令

永久清除历史记录

shell 复制代码
> ~/.bash_history

或

cat /dev/null > ~/.bash_history

变更历史文件位置

修改 HISTFILE 变量

shell 复制代码
export HISTFILE=~/.my_custom_history

设置存储命令的数量

shell 复制代码
export HISTSIZE=1000   # 内存中存储的命令数
export HISTFILESIZE=2000  # 历史文件中存储的命令数

忽略特定命令

shell 复制代码
export HISTIGNORE="ls:pwd:exit"

# 列出的命令将不会保存在历史记录中

忽略重复项

shell 复制代码
export HISTCONTROL=ignoredups

忽略重复的命令和前导空格

shell 复制代码
export HISTCONTROL=ignoreboth

实时将所有命令记录到文件中

shell 复制代码
export PROMPT_COMMAND='history -a'

# 这会将每个命令立即附加到历史记录中

保存时间戳在历史记录中

shell 复制代码
export HISTTIMEFORMAT="%F %T "

现在历史记录将显示:

shell 复制代码
  1  2024-03-31 10:15:30  ls
  2  2024-03-31 10:15:35  cd /home

防止其他用户查看你的历史记录

shell 复制代码
chmod 600 ~/.bash_history

在不同的 Shell 中查看历史记录

  • Bashhistory, ~/.bash_history

  • Zshhistory, ~/.zsh_history

  • Fishhistory, ~/.local/share/fish/fish_history

相关推荐
风曦Kisaki20 分钟前
# Linux Shell 编程入门 Day02:条件测试、if 判断、循环与随机数
linux·运维·chrome
李日灐34 分钟前
< 6 > Linux 自动化构建工具:makefile 详解 + 进度条实战小项目
linux·运维·服务器·后端·自动化·进度条·makefile
嵌入式×边缘AI:打怪升级日志1 小时前
嵌入式Linux开发:开源组件、第三方库与许可证详解
linux
计算机安禾1 小时前
【Linux从入门到精通】第34篇:搭建FTP与Samba——跨平台文件共享解决方案
linux·运维·服务器
日取其半万世不竭1 小时前
用 Netdata 实时监控服务器,比 Prometheus + Grafana 轻量得多
linux·服务器·网络·系统架构·负载均衡·zabbix·grafana
jamon_tan1 小时前
Linux下cmake构建方法
linux
JiaWen技术圈2 小时前
内核子系统 nf_tables 深度解析
linux·服务器·安全·运维开发
计算机安禾2 小时前
【Linux从入门到精通】第32篇:Nginx入门——高性能Web服务器搭建
linux·服务器·nginx
ZenosDoron2 小时前
Linux 中,rm -r 和 -f
linux·运维·服务器
Hello.Reader2 小时前
Ubuntu 上正确安装 Kali 虚拟机、Docker 与 kail 工具指南
linux·ubuntu·docker