如何从Linux/Unix Bash Shell的历史记录中删除单个命令

时间:2020-01-09 10:38:06  来源:igfitidea点击:

在Linux,macOS,* BSD或类似Unix的系统上运行的bash历史记录中如何删除单个命令。

如何删除历史文件中的危险命令?
如何从bash历史记录文件中删除单个命令?
您可以使用history命令清除所有历史记录或选定的命令行。
在本教程中,将学习如何在Linux,MacOS和类似Unix的系统中从bash历史记录中清除特定命令。

如何查看行号的历史记录?

只需输入history命令:

$ history

默认情况下,历史记录存储在~/.bash_history文件中。
但是,名为$HISTFILE的bash变量定义了用于保存命令历史记录的文件名。
如果未设置,则退出shell时不会保存命令历史记录。
使用printf命令/echo命令显示当前设置:

echo "$HISTFILE"
printf "Bash history file - %s\n" $HISTFILE

如何在Linux中从历史记录中删除单个命令号1013

## Delete the bash history entry at offset OFFSET ##
history -d offset
history -d number
history -d 1013

验证一下:

$ history

在位置OFFSET处删除bash历史记录条目。
负偏移量从历史记录列表的末尾算起。

如何删除所有历史记录?

是否要删除所有bash历史记录?
尝试以下语法:

$ history -c

将以上命令添加到~/.bash_logout文件中以在注销时进行清理:

$ cat /dev/null > ~/.bash_history && history -c

传递给历史命令的-c通过删除所有条目${HISTFILE}来清除历史列表。

提示:像专家一样控制bash历史记录

首先,您可以通过在~/.bashrc文件中追加以下配置选项来增加bash历史记录的大小:

## Set the  maximum  number of lines contained in the history file ##
HISTFILESIZE=5000000
 
## Set the number of commands to remember in the command history ##
HISTSIZE=10000
 
## Append it ##
shopt -s histappend
 
######
# Controlling how commands are saved on the history file ##
# ignoreboth means:                       ##
# a) Command which begin with a space character are not saved in the history list               ##
# b) Command matching the previous history entry  to  not  be  saved (avoid duplicate commands) ##
######
HISTCONTROL=ignoreboth

保存并关闭文件。

在其中可以找到有关历史命令的更多信息?

通过执行以下命令来阅读bash手册页:

$ man bash

另一个选择是执行以下命令:

$ help history

输出示例:

history: history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]
    Display or manipulate the history list.
 
    Display the history list with line numbers, prefixing each modified
    entry with a '*'.  An argument of N lists only the last N entries.
 
    Options:
      -c	clear the history list by deleting all of the entries
      -d offset	delete the history entry at offset OFFSET.
 
      -a	append history lines from this session to the history file
      -n	read all history lines not already read from the history file
      -r	read the history file and append the contents to the history
    	list
      -w	write the current history to the history file
    	and append them to the history list
 
      -p	perform history expansion on each ARG and display the result
    	without storing it in the history list
      -s	append the ARGs to the history list as a single entry
 
    If FILENAME is given, it is used as the history file.  Otherwise,
    if $HISTFILE has a value, that is used, else ~/.bash_history.
 
    If the $HISTTIMEFORMAT variable is set and not null, its value is used
    as a format string for strftime(3) to print the time stamp associated
    with each displayed history entry.  No time stamps are printed otherwise.
 
    Exit Status:
    Returns success unless an invalid option is given or an error occurs.