Ubuntu – How to save a part of command lines into a new file using history command

bashcommand line

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!

Best Answer

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