0

I was wondering if there is any way to differentiate whether the input is from stdin or echo command?

i.e.

echo 1 | some_command

OR

execute some_command and it will prompt for the input.

If I enter invalid input in the first case, it leads to infinite loop, screwing all of my error handlings.

It works perfectly fine for 2nd case.

Any ideas?

More output information on the command

$ echo -1 | some_command
Invalid Id:
        Id must be positive!
Invalid selection.
Enter valid Id ('d' re-display, 'q' exit):
Invalid Id:
        Id must be positive!
Invalid selection.
Enter valid Id ('d' re-display, 'q' exit):
Invalid Id:
        Id must be positive!
Invalid selection.
Enter valid Id ('d' re-display, 'q' exit):
Invalid Id:
        Id must be positive!
Invalid selection.
Enter valid Id ('d' re-display, 'q' exit):
Invalid Id:
        Id must be positive!
Invalid selection.
.
.
.
.
konsolebox
  • 72,135
  • 12
  • 99
  • 105
user1228352
  • 569
  • 6
  • 21

1 Answers1

2

Assuming some_command is a script you own and can change:

#!/bin/bash

if [ -t 0 ]
then
    # I am being run directly
else
    # I am being piped input from somewhere else
fi

See also: How to detect if my shell script is running through a pipe?

In response to your comments, hopefully this gives you some pointers:

int main(int argc, char *argv[])
{
    int is_terminal = isatty(0);
    FILE *input = stdin;

    read_input_from(input);

    if (!input_is_valid()) {
        if (!is_terminal) {
            input = fopen("/dev/tty", "r");

            read_input_from(input);
        }
    }

    return 0;
}
Community
  • 1
  • 1
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • Thanks for the way. Can I use this in C as well? I mean because my command is a C program executable. – user1228352 Jul 23 '14 at 15:11
  • http://stackoverflow.com/questions/1061575/detect-in-c-if-outputting-to-a-terminal – Sean Bright Jul 23 '14 at 19:46
  • Hi, Thanks, This solves the detection problem. Now, if wrong input is given from pipe, then it goes into infinite loop. So is there any way to change stdin to direct input when input received from pipe is invalid? – user1228352 Jul 24 '14 at 11:06