Shell – Can the shell warn me if a program is waiting for standard input

shellstdin

Let's say I want to search for a string in a big file: grep foo bar.txt | less, but I actually type grep foobar.txt | less. Now, grep is waiting for me to type something on the terminal. It appears that the command is taking forever, until I notice my mistake.

Can the shell (any shell, or perhaps tmux) detect that a command is waiting for console input, and warn me?

Edit: It seems like each process has a standard input, and the shell has no way of knowing if it's actually waiting for something to arrive there. However, shells like zsh know the command line arguments for common commands like grep and could therefore warn me for the programs it knows.

(grep fTab does not try to complete anything, grep foo bTab will try to complete the filename.)

Best Answer

If you know you're never going to use grep to read from the terminal, you could redefine grep as:

grep() {
  if [ -t 0 ]; then
    < /dev/null command grep "$@"
  else
    command grep "$@"
  fi
}

That will not give you any warning about you typo. But at least it will return without a match immediately. It will also affect behaviour when - or /dev/stdin is passed as an argument to grep.

Edit:

Actually, a way to get a warning would be to close stdin instead of redirecting it from /dev/null:

grep() {
  if [ -t 0 ]; then
    <&- command grep "$@"
  else
    command grep "$@"
  fi
}

$ grep foobar.txt
grep: (standard input): Bad file descriptor