I teach in various CLI tools like git,docker etc. I want to have two bash terminals: one for running commands, and get output, and one that at all time just mirroring what the command history would give me.

Is it possible to mirror realtime commands in bash like that?


T1: pwd

T1: /home/me

T1: ls

T1: Documents Desktop Downloads



3 Answers 3


So, lets split the problem into two parts:

First, you need to make sure, that bash history is being updated immediately. Everytime you type any input and hit enter, the command should be written to .bash_history.

This can be achieved by adding something like following into your .bashrc:

PROMPT_COMMAND='history -a; history -c; history -r'

Second, you want to read the .bash_history file constantly. For that you can use the tail command in your second terminal:

tail -f .bash_history

the -f parameter means, that tail keeps the file open and prints new line as they are being written.


If you need to have the command printed before it is executed, it is fairly complicated using a bash DEBUG trap, but look at this answer and the long version. Here's a simple version. Create a file, say ~/traceme with contents:

# run preexec on each cmd before execute it
# see https://superuser.com/a/175802/458747
    echo "$1" >>~/myhistory
    [ -n "$COMP_LINE" ] && return  # do nothing if completing
    # don't cause a preexec for $PROMPT_COMMAND
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return 
    local this_command=$(HISTTIMEFORMAT= history 1 | 
                                         sed -e "s/^[ ]*[0-9]*[ ]*//");
    preexec "$this_command"
trap 'preexec_invoke_exec' DEBUG

and in your T1 terminal do source ~/traceme. Then in T2 do tail -f ~/myhistory. Every command you enter in T1 will be written to the end of the file that is tailed in T2, before it is executed.


Don't know if this is a viable option for you as you asked about bash. But zsh writes history directly to .zsh_history. So you could have one terminal tail -f .zsh_history. And use another zsh terminal for the actual commands.

But that is if you are willing to use zsh.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .