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

时间:2017-08-10 18:25:39

标签: bash terminal

反向搜索示例:

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

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

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

1 个答案:

答案 0 :(得分:4)

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

搜索空间来源

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

/* 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

如何存储历史

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

算法

使用_rl_isearch_dispatch()_rl_search_getchar()功能执行实际搜索。

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

中的具体详情

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

相关问题