10

I use multiple bash sessions, and I want to keep track of history from all of them in one file (I don't care that it is multiplexed from multiple sessions, I can always put a session identifier in front of it.) I have tried doing

shopt -s histappend

and also adding

history -a 

to the $PROMPT_COMMAND variable. But none of them really work for me, and I don't understand why they don't work (they behave very non-deterministically as far as I can tell... sometimes they multiplex commands from multiple sessions, sometimes they don't).

The goal of this question is to explore an alternate way to keep history from all sessions, where I can control what I write to the history. The idea is to store "previous command" in a shell variable and then echo that variable to a history-log file inside the definition of PS1 variable.

The question is: How do I get the "previous executed command" in a shell variable. I know I can execute echo !! >> logfile.txt in interactive bash session to record it to a log file. But how do I do this in a script file (or .bashrc file)?

I have tried

PROMPT_COMMAND="PC=$_;"
PREVIOUS_COMMAND=$(echo $PC)  # $_ only gives the last argument of previous command
export PS1="[\u@\h \w] [$PREVIOUS_COMMAND $(echo $_) $_] $ "

But none of this works.

Thanks for your time, ~yogi

Yogeshwer Sharma
  • 3,647
  • 5
  • 25
  • 27

1 Answers1

15

Something like

fc -ln -1

should work. That said, you're probably running into concurrent access issues (read: multiple shells overwriting each others' history) and you may not be able to do any better by hand.

geekosaur
  • 59,309
  • 11
  • 123
  • 114
  • Wow! That was quite quick, and exactly what I was looking for. I have checked the concurrency issues already. I just asked two bash scripts to blast current timestamps and append them to a text file for 10 seconds. The output lines were in some order, but each line was from either one of the scripts, not a combination of two lines from two different scripts. I hope this is the right behaviour when you append to a text file. – Yogeshwer Sharma Jul 20 '11 at 02:43
  • 1
    I am now writing export PS1=[\`fc -ln -1\` : $(fc -ln -1) : \`date\`] and I don't get what I want. The date prints fine, but fc output does not. Any ideas what I am doing wrong? – Yogeshwer Sharma Jul 20 '11 at 02:51
  • Yu would need single quotes in there to prevent the `` ` `` or `$()` from being expanded during its definition. `export PS1='[$(fc -ln -1) : $(date)] '` or something similar — although I have to wonder if some formatting went missing there. – geekosaur Jul 20 '11 at 03:58
  • Yeah, I had those quotes in place. Still not doing what it is supposed to do! :-( – Yogeshwer Sharma Jul 20 '11 at 07:45