我想知道是否有办法区分输入是来自stdin还是echo命令?
即
echo 1 | some_command
OR
执行some_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.
.
.
.
.
答案 0 :(得分:2)
假设some_command
是您拥有并可以更改的脚本:
#!/bin/bash
if [ -t 0 ]
then
# I am being run directly
else
# I am being piped input from somewhere else
fi
另请参阅:How to detect if my shell script is running through a pipe?
回应您的意见,希望这能为您提供一些指示:
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;
}