如何在 bash 脚本中获得“先前执行的命令”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6756360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get "previous executed command" in a bash script?
提问by Yogeshwer Sharma
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
我使用多个 bash 会话,我想在一个文件中跟踪所有这些会话的历史记录(我不在乎它是从多个会话中复用的,我总是可以在它前面放一个会话标识符。)我有尝试做
shopt -s histappend
and also adding
并添加
history -a
to the $PROMPT_COMMANDvariable. 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).
到$PROMPT_COMMAND变量。但是它们都没有真正对我有用,我不明白为什么它们不起作用(据我所知,它们的行为非常不确定......有时它们会从多个会话中复用命令,有时它们不会)。
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 PS1variable.
这个问题的目标是探索另一种方法来保留所有会话的历史记录,在那里我可以控制我向历史记录的内容。这个想法是将“上一个命令”存储在一个 shell 变量中,然后将该变量回显到变量定义内的历史日志文件中PS1。
The question is: How do I get the "previous executed command" in a shell variable. I know I can execute echo !! >> logfile.txtin interactive bash session to record it to a log file. But how do I do this in a script file (or .bashrc file)?
问题是:如何在 shell 变量中获取“先前执行的命令”。我知道我可以echo !! >> logfile.txt在交互式 bash 会话中执行以将其记录到日志文件中。但是如何在脚本文件(或 .bashrc 文件)中执行此操作?
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
谢谢你的时间,〜yogi
回答by geekosaur
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.
应该管用。也就是说,您可能会遇到并发访问问题(阅读:多个 shell 覆盖彼此的历史记录)并且您可能无法手动做得更好。

