Is there an environment variable you can use in Linux to send your command history to a different file?

The reason I ask is that I'm interested in recording my shell sessions into different files for referencing later.

I know I could use auditd or something like that, but that's an awful lot to setup for just recording my sessions, so I thought I'd ask if there's an environment variable or something I could use instead.

  • set | grep HIST? – Cyrus Sep 27 '19 at 19:46
  • 2
    You can always do history -a <FILE> at the end of each session to save current subshell's history. – Arkadiusz Drabczyk Sep 27 '19 at 19:50
  • @ArkadiuszDrabczyk you should make that an answer (possibly along with mentioning HISTFILE which Cyrus seems to be alluding to.) – derobert Sep 27 '19 at 20:03

I have recently answered a very similar question asked at Ask Ubuntu: https://askubuntu.com/questions/1175757/how-can-i-save-a-part-of-command-lines-into-a-new-file-using-history-command/1175763#1175763

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.