On korn shell, how to share history between regular user and root?

I'm exploring OpenBSD and want to stick to its default shell, which is ksh. My goal is for my regular user ("bruno") and root user to have a shared history file. However, it seems that when running as root, ksh refuses to write to a HISTFILE that is owned by non-root user. This illustrates the issue:

$ echo $0
  ksh
$ HISTFILE=/home/bruno/history  
$ chmod 777 /home/bruno/history
$ echo test
  test
$ cat /home/bruno/history
  chmod 777 /home/bruno/history
  echo test
  cat /home/bruno/history
$ su
 Password:
# HISTFILE=/home/bruno/history
# echo $HISTFILE
  /home/bruno/history
# echo test2
  test2
# cat /home/bruno/history
  chmod 777 /home/bruno/history
  echo test
  cat /home/bruno/history
  su
   

As you can see, the commands that are run as root do not appear in /home/bruno/history. Why won't root session in ksh write to the specified HISTFILE? If it is a ksh security feature, how do I turn it off?

Why not write a little cron script to combine the two files?

That's a good idea, but I wanted something more real-time, so I came up with a hack. If I put this in both ~/.kshrc and /root/.kshrc, I get what I want:

prompt_commands()
{
    if [ $(id -u) = "0" ]; then
        tail -1 /root/.ksh_history >>/home/bruno/.ksh_history
    else
        tail -1 /home/bruno/.ksh_history >>/root/.ksh_history
    fi
}

PS1='$(prompt_commands)'

Unlike bash, ksh does not have the handy PROMPT_COMMAND. However, the PS1 variable does support command substitution, which my hack exploits. As long as both user's and root's history files have write permission for "others", now whenever root runs a command that command gets appended to my regular user's history, and vice-versa.

1 Like

I like your solution better than my suggestion.

Thanks for posting back what you came up with!