Monil Vikam
Monil Vikam

Reputation: 181

History command does not work when HISTFILE variable is set

We have a common Linux test env where multiple people work(connect through ssh using Putty), We have a requirement to store commands fired from all terminals in such a way that we can track each and every command, fired by which IP/user and from which TTY so that we can verify it using 'last' command.

I have changed my .bash_profile accordingly

# Will Give me ip of person logged in
WHOAMI=`who -m | cut -d '(' -f 2| cut -d ')' -f1`  
# Will give me tty ID
MYTTY=`who -m | awk '{print $2;}' | cut -d '/' -f2`
DATE=`date +"%Y_%m_%d_%H%M%S"`
DAY=`date +"%Y_%m_%d"`
shopt -s histappend
mkdir -p $HOME/HISTORY/${WHOAMI}/${DAY}
touch $HOME/HISTORY/${WHOAMI}/${DAY}/.HIST_${MYTTY}_${DATE}
export HISTTIMEFORMAT='%F %T '
export HISTFILESIZE=100
export HISTSIZE=100
# stores history file per terminal
export HISTFILE=$HOME/HISTORY/${WHOAMI}/${DAY}/.HIST_${MYTTY}_${DATE}
export PS1='[\[\e[4;32m\]\u@\h\[\e[0m\] \[\e[1;36m\]$PWD\[\e[0m\]]\! $'
# Updates the HISTFILE at real time i.e. when user presses enter
export PROMPT_COMMAND="history -a; history -c; history -r; ${PROMPT_COMMAND}"
history -r $HISTFILE

After changing the .bash_profile, the history command stopped showing previous entries.

When I changed PROMPT_COMMAND to "history -a; history -r; ${PROMPT_COMMAND}" it started working but

  1. The HISTFILE is not updated at real time; it's only updated when exit command is fired.

  2. If user disconnects the putty session by right click and using disconnect option, HISTFILE is not updated at all. :(

P.S:- If i comment export HISTFILE it stores to .bash_history file and everything works smoothly and .bash_history is updated in real time, but I do not get the tty id or IP from which command was fired

O.S:- Red Hat Enterprise Linux Server release 6.8 (Santiago)

Upvotes: 3

Views: 2938

Answers (1)

Monil Vikam
Monil Vikam

Reputation: 181

Replacing

touch $HOME/HISTORY/${WHOAMI}/${DAY}/.HIST_${MYTTY}_${DATE}

with

printf "#`date '+%s'`\nll\n" > $HOME/HISTORY/${WHOAMI}/${DAY}/.HIST_${MYTTY}_${DATE}

Did the trick, so it seems that only if there is some data in HISTFILE file, history command updates it properly at real time else it updates it only when exit command is fired.

Upvotes: 3

Related Questions