C++ 简单交互 shell 重定向输入时提示隐藏

C++ simple interactive shell prompt hiding when redirecting input

我正在用 C++ 编写一个简单的交互式 shell 程序。它应该与 shbash.

类似

程序如下所示(尽可能简化):

#include <iostream>
#include <string>

int main(){
    std::string command;

    while (1){
        std::cout << "prompt> ";
        std::getline(std::cin, command);
        std::cout << command << std::endl;
        if (command.compare("exit") == 0) break;
    }

    return 0;
}

它可以根据需要与人进行交互。它提示,用户写命令,shell执行它。

但是,如果我 运行 shell 这样 ./shell < test.in (重定向输入),它会产生带有 shell 提示的输出,如下所示:

prompt> echo "something"
prompt> echo "something else"
prompt> date
prompt> exit

它确实产生了正确的输出(在这种情况下只是输出输入字符串)但是它 'poluted' 有提示。

在重定向输入时,是否有一些相当简单的方法来摆脱它(如果我对例如 bash 做同样的事情,输出中没有提示)? 提前谢谢你

cheers-and-hth-alf 提出的解决方案对我有效。谢谢

解决方案:

#include <iostream>
#include <string>
#include <unistd.h>

int main(){
    std::string command;

    while (1){
        if (isatty(STDIN_FILENO)){
            std::cout << "prompt> ";
        }
        std::getline(std::cin, command);
        std::cout << command << std::endl;
        if (command.compare("exit") == 0) break;
    }

    return 0;
}

假设您 运行 在 *NIX 类型的系统上,您可以(并且应该)使用 isatty 来测试 stdin 是否连接到 tty(交互式终端)。

像这样的东西会起作用:

if (isatty(STDIN_FILENO)) {
    std::cout << "prompt> ";
} // else: no prompt for non-interactive sessions