Search code examples
c++shellprompt

C++ simple interactive shell prompt hiding when redirecting input


I am writing a simple interactive shell program in C++. It should work simalary to sh or bash.

Program looks like this (simplified as much as possible):

#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;
}

It works as desired with human interaction. It prompts, user writes command, shell executes it.

However, if I run shell like this ./shell < test.in (redirect input) it produces output with shell prompts like this:

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

It does produce correct output (just output input string in this case) but it is 'poluted' with prompts.

Is there some rather simple way to get rid of it (if I do the same with e.g. bash there is no prompt in output) when redirecting input? Thank you in advance


Solution

  • Assuming you're running on a *NIX-type system, you can (and should) use isatty to test whether stdin is connected to a tty (interactive terminal).

    Something like this will work:

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