Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get "previous executed command" in a bash script?

Tags:

bash

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

like image 306
Yogeshwer Sharma Avatar asked Jul 20 '11 02:07

Yogeshwer Sharma


1 Answers

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.

like image 178
geekosaur Avatar answered Oct 23 '22 20:10

geekosaur