Is there any way to check history only of current session?

I wanted to know if there is any command or any other way I can check my command history only in the current session.


Solution 1:

The history built in bash allows specifying filenames when used with -anrw flags, and -a flag description from help history states:

append history lines from this session to the history file

Therefore, we can do:

~$ history -a this_session.history
~$ cat ./this_session.history 
history mysession.history 
cat mysession.history 
clear
history -a this_session.history

For the record, -w (the write history to file opion) writes whole history to the specified file, so -a (append) here is preferred choice.


There's other manual ways. In particular ksh doesn't have -a flag as bash does, but what ksh and mksh do have is HISTFILE environment variable ( and bash has that,too, because bash included lots of ksh features); by the way, this variable by default isn't set (at least mksh on Ubuntu didn't set it). So, for outputting current session to other file, we call HISTFILE prepended to command which in shell syntax means running command with additional environment variable you specify. Like so:

bash-4.4$ HISTFILE='mykshfile.hist' ksh
$ echo 'Hello'
Hello
$ echo 'World'
World
$ 
bash-4.4$ cat ./mykshfile.hist 
�echo 'Hello'
echo 'World'

What you also can see from this is that ksh and its related shells output history with special characters, instead of plain text as what bash does. So, you may want to open that file with ksh.

As far as the POSIX /bin/sh shell on Ubuntu, which is Debian Almquist Shell or Dash, there exists fc built-in. However, on Ubuntu dash is compiled without lib-edit, which is a conscious choice by Ubuntu developers for performance reasons, so fc and other modes that require line editing don't work out of the box (unless recompile dash yourself and install lib-edit).


Shell neutral ways would be to record your session with existing tools or write your own function to record on per-command basis.