In a bash shell, when I run history, it provides the history of all the commands not only those typed in the current shell, but also those in the previous shells. How can I get the history of the commands only typed in the current shell so far? This is useful when you want to find a command that you know has been typed in the current shell. Thanks.

  • No Tim, that is not possible with a simple bash history. To do that you would need the PID of the bash executing the command (at least). This show a way to get a permanent history, but that doesn't work with a vanilla bash history. – Isaac Dec 18 '16 at 6:43

Provided that histappend is not set and no games are played with PROMPT_COMMAND, the history command can:

  -a   Append the ``new'' history lines (history lines entered 
       since the beginning of the current bash session) to 
       the history file.

If we want to leave our real history file unharmed, we could do:

$ cat .bash_history

$ echo "one more command"
one more command

$ echo "another command"
another command

$ HISTFILE=foo history -a
$ cat foo
cat .bash_history
echo "one more command"
echo "another command"
HISTFILE=foo history -a

The previous commands from earlier sessions (ls, date, free) do not show up in our "new" history file, foo - I hope the example brings across that point.

Another approach would be to save the current history file (at the beginning of the login session!) and then later append the current session's history to the history file (either by running "history -a" or by logging out) and then compare both files:

$ history > hist.backup

$ echo "a new command"
a new command
$ echo "one more command"
one more command

$ history > hist.current 
$ diff hist.{backup,current}
>     5  2016-12-17 19:38:57 echo "a new command"
>     6  2016-12-17 19:39:01 echo "one more command"
>     7  2016-12-17 19:39:07 history > hist.current 

Note: I'm a huge fan of setting HISTTIMEFORMAT='%F %T ' (introduced in bash 3, IIRC), timestamps help a lot to find out when a command was executed.


Use comp to compare the entire history (incl. current Bash session) with the already persisted history in .bash_history and only print those lines that are unique to the current session -- which should show only those commands that were executed since starting the current Bash shell

comm -23 <( history | cut -c 8- ) ~/.bash_history

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.