0

以前我写了一个脚本,将我以前访问过的目录记录到 sqlite3 db。我写了一些快捷方式来快速搜索和浏览历史。现在我正在考虑对我的 bash 命令做同样的事情。

当我在 bash 中执行命令时,如何获取命令名称?我是否必须更改负责编写 bash 历史的 bash 源代码部分?一旦我有了我的命令历史数据库,我就可以在其中进行智能搜索。

4

5 回答 5

3

很抱歉这么晚才来回答这个问题!

我倾向于在我工作的地方运行很多 shell,因此长期运行的 shell 历史会一直混淆或丢失。我终于受够了,我开始登录数据库:)

我还没有完全完成集成,但这是我的设置:

  1. 在启用 SYSLOG 的情况下重新编译 bash。由于 bash 版本 4.1,此代码已全部到位,因此只需要在 config-top.hi 中启用即可。
  2. 安装新的 bash 并配置您的 syslog 客户端以记录 user.info 消息
  3. 安装 rsyslog 和 rsyslog-pgsql 插件以及 postgresql。如果您遇到问题或在这里提问,我在 debian 测试中安装它时遇到了一些问题,请 PM 我 :)
  4. 配置用户消息以馈入数据库。

最后,您的所有命令都应记录到名为 systemevents 的表中。如果您经常使用 shell,您肯定会希望在几个字段上设置索引,因为查询可能会开始永远花费:)

以下是我设置的几个索引:

索引: "systemevents_pkey" PRIMARY KEY, btree (id) "systemevents_devicereportedtime_idx" btree (devicereportedtime) "systemevents_fromhost_idx" hash (fromhost) "systemevents_priority_idx" btree (priority) "systemevents_receivedat_idx" btree (receivedat)

fromhost、receivedat 和 devicereportedtime 特别有用!

从我使用它的很短的时间开始,这真是太棒了。它让我可以在我最近使用的任何服务器上找到命令!再也不会失去命令了!如果您有多个用户,您也可以将其与停机时间/其他问题相关联。

我计划编写自己的 rsyslog 插件,以使数据库中的历史记录格式更有用。当我这样做时会更新:)

祝你好运!

于 2014-08-01T19:04:16.987 回答
1

Bash 已经将所有命令记录到 ~/.bash_history 中,这是一个纯文本文件。

您可以使用向上/向下箭头浏览内容,或按 搜索内容control-r

于 2013-07-02T04:04:42.380 回答
1

看看fc

fc: fc [-e ename] [-lnr] [first] [last] 或 fc -s [pat=rep] [command] 显示或执行历史列表中的命令。

fc is used to list or edit and re-execute commands from the history list.
FIRST and LAST can be numbers specifying the range, or FIRST can be a
string, which means the most recent command beginning with that
string.

Options:
  -e ENAME    select which editor to use.  Default is FCEDIT, then EDITOR,
      then vi
  -l  list lines instead of editing
  -n  omit line numbers when listing
  -r  reverse the order of the lines (newest listed first)

With the `fc -s [pat=rep ...] [command]' format, COMMAND is
re-executed after the substitution OLD=NEW is performed.

A useful alias to use with this is r='fc -s', so that typing `r cc'
runs the last command beginning with `cc' and typing `r' re-executes
the last command.

Exit Status:
Returns success or status of executed command; non-zero if an error occurs.

您可以调用它来获取要插入到表格中的文本,但是如果它已经被 bash 保存了,为什么还要麻烦呢?

于 2013-07-02T04:22:17.327 回答
1

您可以使用Advanced Shell Historyash_query工具将您的 shell 历史记录写入 sqlite3 并使用提供的工具从命令行查询数据库。

vagrant@precise32:~$ ash_query -Q
Query    Description
CWD      Shows the history for the current working directory only.
DEMO     Shows who did what, where and when (not WHY).
ME       Select the history for just the current session.
RCWD     Shows the history rooted at the current working directory.

您可以编写自己的自定义查询,也可以从命令行使用它们。

除了命令之外,该工具还为您提供了许多额外的历史信息——您可以获得退出代码、开始和停止时间、当前工作目录、tty 等。

完全披露 - 我是作者和维护者。

于 2014-08-30T19:21:03.543 回答
0

为了获得完整的历史记录,请使用 history 命令并处理其输出:

$ history > history.log

或使用以下命令刷新历史记录(因为它由 BASH 保存在内存中):

  $ history -a

然后处理 ~/.bash_history

于 2014-01-10T00:45:07.813 回答