4

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!

SRMZ
  • 41

4 Answers4

2

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
1

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

Raffa
  • 32,237
0

an inferior answer but it works,

type history to get the history. mouse swipe want you want to copy ctrl-shift-c to copy and ctrl-v to paste into a text editor.

in my case, terminal was konsole and text editor was kate.

this lets you copy and paste selected parts of the history.

also lets you copy and paste into the terminal from history , crtl-shift-v to paste

pierrely
  • 653
0

You could skip the above answers by putting the bash history in a seperate, per-session file to begin with.

See my answer Bash history handling with multiple terminals

waltinator
  • 36,399