Bash script to detect last command runned in terminal

428 views Asked by At

I have to make a script that print all commands used by user. So I try to make a script that will run in background and which deletes history and registers every command runned from that moment and echo it in a file. This is what I did but it doesn't work.

function add_new_command() {
    nr=$(history | wc -l)
    
    if [ $nr -eq 1 ]; then 
        comanda=$(history | head -n 1)
        echo $comanda > mycommands
        history -c
    fi
}

history -c
while true
do
add_new_command
done
2

There are 2 answers

0
tripleee On

A much better approach is to use the built-in variables for controlling history.

history -c
BASH_HISTORY=mycommands
0
AudioBubble On

I made a change and i think it gonna work now. I added next 2 lines in ~/.bashrc:

    shopt -s histappend
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"

and now all command from more than 1 terminal are instantly copy in ~/.bash_history . so all i need to do is to copy that file.