c - 如何用C语言创建一个可以实现向上箭头历史捕获的shell?

标签 c linux shell

我已经把之前命令的历史记录保存在一个二维数组中了。但我不知道如何检查向上箭头。

如何使用 C 编程语言实现此功能(在 Linux 中)?

最佳答案

感谢 n.m. 的好建议。

下面是libreadline的使用示例:

// rltest.c
#include <stdio.h>
#include <stdlib.h>
#include <readline.h>
#include <history.h>

int main(void)
{
    char* input, shell_prompt[100];
    // Configure readline to auto-complete paths when the tab key is hit.
    rl_bind_key('\t', rl_complete);
    // while work is not 0 program executes the loop
    int work = 1;
    printf("Commands to use: name, ver, exit \n");
    // loop for working with commands
    while(work) {
        // Build prompt string.
        snprintf(shell_prompt, sizeof(shell_prompt), "your command $ ");
        // Display prompt and read input
        input = readline(shell_prompt);
        // Check for EOF.
        if (!input)
            break;
        // Add input to history.
        add_history(input);
        // Command analysis and execution
        if( 0 == strcmp(input, "exit") )
        {
            printf("Bye!\n");
            work = 0;
        }
        if( 0 == strcmp(input, "name") )
        {
            printf("I'm readline example\n");
        }
        if( 0 == strcmp(input, "ver") )
        {
            printf("My version is 0.1\n");
        }
        // ...
        // Free input for future use
        free(input);
    }
    return 0;
}

编译这个例子:

1) 安装readline库

 apt-get install libreadline-dev

2) 编译程序为

 gcc rltest.c -I/usr/include/readline -lreadline

关于c - 如何用C语言创建一个可以实现向上箭头历史捕获的shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28824064/

相关文章:

java - java中设置HDFS的空间配额

linux - 如何在 linux 中的 postscript 或 pdf 文件的每一页底部添加页脚?

linux - shell 脚本 : Hexadecimal Loop

c - 欧拉项目的问题 8 没有显示输出

c++ - 构建由 C 和 C++ 文件组成的库

linux - 是否有必要在每个二分步骤后清理 Linux 内核源代码树?

mysql - shell脚本中mysql存储过程的关联数组

c - 链接共享库后符号丢失

c - 当尝试从 bmp 文件中提取 RGB 分量时,为什么我的代码段出现错误?

linux - 对带有日期的变量进行操作会产生错误