如何在bash终端中实现CTRL-R(反向搜索)?

问题描述 投票:5回答:1

反向搜索示例:

(reverse-i-search)`grep': git log | grep master

用于查找建议的算法是什么?它的搜索空间来自哪里?

非常感谢指向其源代码的指针。

bash terminal
1个回答
4
投票

反向搜索是GNU Readline Library的一部分。 Readline库有助于阅读线和编辑设施。整个源代码可以找到here

Source of search space

以下源代码片段显示了如何确定历史记录的源文件:

/* Return the string that should be used in the place of this
   filename.  This only matters when you dont specify the
   filename to read_history (), or write_history (). */
static char *
history_filename (filename)
     const char *filename;
{
  char *return_val;
  const char *home;
  int home_len;

  return_val = filename ? savestring (filename) : (char *)NULL;

  if (return_val)
    return (return_val);

  home = sh_get_env_value ("HOME");
#if defined (_WIN32)
  if (home == 0)
    home = sh_get_env_value ("APPDATA");
#endif

  if (home == 0)
    return (NULL);
  else
    home_len = strlen (home);

  return_val = (char *)xmalloc (2 + home_len + 8); /* strlen(".history") == 8 */
  strcpy (return_val, home);
  return_val[home_len] = '/';
#if defined (__MSDOS__)
  strcpy (return_val + home_len + 1, "_history");
#else
  strcpy (return_val + home_len + 1, ".history");
#endif

  return (return_val);
}
  • savestring()savestring.c中定义,如果定义了字符串,则只复制字符串filename
  • sh_get_env_value()函数是使用getenv()函数(由<stdlib.h>提供)实现的,用于获取环境值(参考man page getenv(3))。
  • 如图所示,.bash_history.history(这是函数返回NULL时使用的文件)将用作在Linux系统上实现搜索的源。

资料来源:histfile.c

How history is stored

  • 可搜索的历史存储在HIST_ENTRY(历史列表)数组中。来自.bash_history的数据被添加到此数组中。资料来源:history.c
  • 在当前会话中输入的命令记录保存在_rl_saved_line_for_history中。
  • 这两个被组合成一个_rl_search_cxt实例成员数组(cxt->lines[]),使用它进行搜索。

Algorithm

使用_rl_isearch_dispatch()_rl_search_getchar()函数执行实际搜索。

简短摘要:算法逐字逐句地读取输入决定它应该做什么。如果没有中断,它会将字符添加到搜索字符串中,在数组中搜索它。如果找不到该字符串,它将移动到下一个元素,跳过再次找到的相同字符串,并且字符串的长度比搜索字符串的当前长度短。 (阅读default :中的switch,了解_rl_isearch_dispatch()的具体细节)

如果没有找到字符串,则响铃。否则,它会显示字符串,但实际上并未在历史列表中移动,直到用户接受该位置。

© www.soinside.com 2019 - 2024. All rights reserved.