3

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?

Example:

T1: pwd

T1: /home/me

T1: ls

T1: Documents Desktop Downloads

T2:

pwd
ls
2

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.

| improve this answer | |
0

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:

#!/bin/bash
# run preexec on each cmd before execute it
# see https://superuser.com/a/175802/458747
preexec(){ 
    echo "$1" >>~/myhistory
}
preexec_invoke_exec(){
    [ -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.

| improve this answer | |
0

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.

| 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.