是否可以查看另一个 shell 的历史记录?

是否可以查看另一个 shell 的历史记录?

我正在窗口中运行一些bash我不想中断甚至暂时暂停的东西。是否可以查看该特定窗口会话的命令历史记录?我打开了多个窗口,所以查看.bash_history没有多大帮助。

答案1

以下是如何使用gdb(您需要以管理权限运行它),通过https://stackoverflow.com/questions/7272558/can-we-define-a-new-data-type-in​​-a-gdb-session

准备:

echo 'typedef void * histdata_t;
typedef struct _hist_entry {
  char *line;
  char *timestamp;
  histdata_t data;
} HIST_ENTRY;
typedef struct _hist_state {
  HIST_ENTRY **entries;
  int offset;
  int length;
  int size;
  int flags;
} HISTORY_STATE;
HIST_ENTRY _sampleentry;
HISTORY_STATE _samplestate;
' | tee sample.c
# get sample.o
gcc -g -c sample.c

# get bash pid, maybe via `pgrep bash`, or `pidof bash`, etc
# say in this example, it is 16573

运行测试命令:

$ sudo gdb -p 16573 -ex "set confirm off" -ex "add-symbol-file sample.o 0" -ex 'printf "ptype HIST_ENTRY\n"' -ex "ptype HIST_ENTRY" -ex 'printf "p *(HISTORY_STATE*)history_get_history_state()\n"' -ex 'p *(HISTORY_STATE*)history_get_history_state()' -ex 'set $myoffs = (*(HISTORY_STATE*)history_get_history_state())->offset' -ex 'printf "myoffs %d\n", $myoffs' -ex 'printf "p *(HIST_ENTRY *)history_get($myoffs)\n"' -ex 'p *(HIST_ENTRY *)history_get($myoffs)'
....
0x00007fb053abb0e9 in __pselect (nfds=1, readfds=0x7ffe81a009b0, writefds=0x0, exceptfds=0x0, 
    timeout=<optimized out>, sigmask=0x7ffe81a00930) at ../sysdeps/unix/sysv/linux/pselect.c:69
69  ../sysdeps/unix/sysv/linux/pselect.c: No such file or directory.
add symbol table from file "sample.o" at
    .text_addr = 0x0
Reading symbols from sample.o...done.
ptype HIST_ENTRY
type = struct _hist_entry {
    char *line;
    char *timestamp;
    histdata_t data;
}
p *(HISTORY_STATE*)history_get_history_state()
$1 = {entries = 0x55ed117f4ab0, offset = 155, length = 155, size = 502, flags = 1}
myoffs 155
p *(HIST_ENTRY *)history_get($myoffs)
$2 = {line = 0x55ed119684d0 "kill -STOP $$", timestamp = 0x55ed119709a0 "#1545016332", data = 0x0}

准备 gdb“捕获最后的历史条目”命令:

echo '
set verbose off
set complaints 0
set trace-commands off
add-symbol-file sample.o 0
set $myoffs = ((HISTORY_STATE*)history_get_history_state())->offset
set $line = ((HIST_ENTRY *)history_get($myoffs))->line
printf "%s\n", $line
' | tee gdbscript

运行 gdb“捕获最后的历史条目”命令:

sudo gdb -p 16573 -batch -x gdbscript 2>/dev/null | tail -1
kill -STOP $$

答案2

不,bash不支持。历史记录保存在内存中,只有在使用或将其保存到.bash_history同一会话中时,其他进程才可以使用。但是,一旦将其写入文件系统,命令源自哪个会话的信息就会丢失。history -ahistory -w

您可以获得的最接近的是使用一些行来.bashrcbash执行后直接附加每个命令:https://unix.stackexchange.com/a/1292/147970
然后您可以在.bash_history.

要访问特定会话的历史记录,您需要使用例如中断该会话中的前台进程Ctrl+Z

答案3

您可以按 Ctrl-Z 将任务置于后台。之后,您可以在 shell 中工作并查看命令历史记录。要在后台查看任务,您可以使用job命令。要返回您的任务,请运行fg命令。

相关内容