How can I save a part of command lines into a new file using history command?

I am a beginner of bash. I know that type

history

can show all command lines and .bash_history save all of them. But if I want a part of command lines (e.g., current session) and save them into a new file, what should I do? I checked

history --help

and still, do not understand how to do so. Thanks for help in advance!


Solution 1:

You need to use -a together with a file name. As explained in help history:

history: history [-c] [-d offset] [n] or history -anrw [filename] or history -ps arg [arg...]

(...)

-a append history lines from this session to the history file

And later on:

If FILENAME is given, it is used as the history file. Otherwise, if $HISTFILE has a value, that is used, else ~/.bash_history.

For example, start a new session and type this ($ is a prompt, it will most probably be different on your system):

$ echo a-new-session started at $(date)
$ history -a /tmp/new-history

In this case /tmp/new-history will be:

echo a-new-session started at $(date)
history -a /tmp/new-history

Solution 2:

Current session:

You can do so by running the following command in the terminal:

history -a ~/current_session.txt

Current session's history will be saved to a file named current_session.txt in your home directory.


Certain inputs:

You can also search all history for a certain input and save the output to a file. For example to save all lines that have install in them, please run the following command in the terminal:

history | grep install > ~/search_results.txt

Search results will be saved to a file named search_results.txt in your home directory.

Change install to whatever you want to search for.

To search for multiple inputs put them between two quotation marks "" , separate them with a pipe | and put -E before them like so:

history | grep -E "install|update|upgrade" > ~/search_results.txt

Best of luck