History recording mechanism in Bash

Time:2020-3-31

Basic Usage

Show history

UsehistoryYou can view the latest execution of the current userHISTSIZEThese records are stored inHISTFILEIn file, inbashIt is automatically loaded into the history buffer queue at startup, and its simple use method is as follows:

>History displays all history
    1  ip a
    2  exit
    3  ls -la
    4  history
>History 2 displays the last two history records
    4  history
    5  history 2

Search and batch query

UseCtrl + RThe shortcut key can enter the history search mode according to the characters entered by the userMost similar recentlyIn principle, the search results are printed to the command prompt, which can be executed directly by entering enter. Another way is to usegrepBatch search with pipeline:

> history | grep ffmpeg | grep gif | grep yuv444p  
 119  ffmpeg -y -f gif -i 79557166.gif -c:v libx264 -vf format=yuv444p yuv444p.mp4  
 120  ffmpeg -y -f gif -i 79557166.gif -c:v libx264 -vf format=yuv444p yuv444p.mkv

Immediate execution (danger)

Use!!Be able to execute the last command in the history immediately, that is, repeat the previous command; use![number]Can be based onnumberExecute the corresponding numbered history command; use the![string]Can be based onstringaccording toMost similar recentlyPolicy execution history command. The most humanized thing about this kind of command is that it will print the command to be executed before execution (let you know how the system hangs).

> date
Sun 23 Feb 2020 06:18:16 PM CST
>!! Not safe
date  
Sun 23 Feb 2020 06:18:18 PM CST
>! 907 danger
make  
make: \*\*\* No targets specified and no makefile found.  Stop.
>! shut is very dangerous
shutdown now

adopt!It is very dangerous to directly execute the corresponding history of the first command, especially in the high permission user environment. Therefore, it is recommended to view the corresponding command in the following ways before execution:

>!: P ා view the last command in the record
>! 123: P ා view 123rd command in record
>! sys: P ා view the latest command at the beginning of sys in the record

Delete record

Usehistory -d <hist_num>You can delete the history of the specified sequence number. This mode only receives one parameter, and other parameters will be ignored. With this feature, you can execute commands that are not recorded in bash.

> echo "secret command";history -d $(history 1)
secret command

If you want to completely clear the usage traces in the current session, you can use thehistory -cClear the history buffer queue, note that this command does not empty the history file.

[warning]Be careful: in addition to the above methods, users can also use theunset HISTFILECanceling the history function directly is very dangerous for the daily maintenance of the server.

File operation

When exiting the terminal, bash will automatically write the command executed in the current session to the history file. The default writing method is overwrite. You can also pass-wand-aMode to manually write commands from the current session to a file:

>History - w ා buffer queue overwrite write file
>History - a ා the command of the current session appends the write file

advanced setting

withUbuntu 20.04 LTSFor example, by default, environment variables related to history are defined in the~/.bashrcIn the document.

Add timestamp

By modifyingHISTTIMEFORMATVariable to timestamp history,%FRepresentative date,%TRepresents time.

> export HISTTIMEFORMAT='%F %T '
> echo 'history with time'
> history 1
1032  2020-02-23 17:01:26 history

Modify record policy

By modifyingHISTCONTROLVariables can be controlledhistoryThe recording strategy of is shown in the following table:

Optional value Recording strategy
ignoredups Default, no recordcontinuitySame command for
ignorespace Do not record commands starting with spaces
ignoreboth Combination of ignoredups and ignorespace
erasedups Do not record duplicate commands

We can also setHISTIGNOREVariable specifies the command to be ignored, between commands:Separate:

> echo 'export HISTIGNORE="ls:cd"' >> ~/.bashrc
> source ~/.bashrc

Modify storage file

The history of the current user is stored by default to~/.bash_historyIn the file, you can modify theHISTFILEVariable changes the location of the history store.

> echo 'export HISTFILE="<new_histfile_path>"' >> ~/.bashrc
> source ~/.bashrc

Modify storage size

variableHISTSIZEDecided to usehistoryTimedisplayThe default value is1000

> echo $HISTSIZE
1000
>Histsize = 200 - only valid for the current session
>Sed - I's / ^ histsize = 1000 / histsize = 200 / '~ /. Bashrc
> echo $HISTSIZE
200

variableHISTFILESIZEDefinedstorageThe total number of historical commands in the file, the default is2000。 History is stored like a queue,bashInitialization willHISTFILEAll the historical records stored in the file are loaded into the memory and stored in the form of a queue. The commands generated by the user during the use process are also added to the queue, and each time the user callshistoryWill show the latestHISTSIZEBar record.

Modify storage policy

When the terminal exits, the records generated in the current session will be written to the file. In order to prevent the loss of historical records caused by opening multiple terminals at the same time, it is recommended to~/.bashrcAdd to fileshopt -s histappendTo enable the terminal to append the history generated by the current session to theHISTFILEIn the document.

[warning] Be careful: by default, the write mode of history is overwrite. For example: open terminal a – > open terminal B – > Close terminal a – > Close terminal B. This operation sequence will result in the loss of all history records generated by terminal a during operation.

Special circumstances such as power failure and illegal shutdown will causebashUnable to end normally, resulting in the loss of history for the current session. Can be in~/.bashrcAdd the following content to the file to automatically append and write each command:

PROMPT_COMMAND=”history -a”

staybashIf you set thePROMPT_COMMANDEnvironment variable, the command prompt is displayed at each time (for example:[email protected]:~$)Previously, the value of this variable will be executed as a command, here we set it to execute automaticallyhistory -a, append the history to the file.

Recommended Today

PHP Basics – String Array Operations

In our daily work, we often need to deal with some strings or arrays. Today, we have time to sort them out String operation <?php //String truncation $str = ‘Hello World!’ Substr ($STR, 0,5); // return ‘hello’ //Chinese string truncation $STR = ‘Hello, Shenzhen’; $result = mb_ Substr ($STR, 0,2); // Hello //First occurrence of […]