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
The commands that read stdin
are almost all of the filter family, i.e. programs that transform a flow of text data to a transformed one.
cat
, sed
, awk
, gzip
and even sh
are good examples of such "filters".
The cited commands, cp
, mv
and rm
are definitely not filters but commands that do things with the arguments passed, here files or directories.
The cd
command is similar to them, it expects an argument (or simulate a default one if not provided), and generally doesn't output anything on stdout
, although it might output something on it in some cases like when using CDPATH
.
Even if one want to create a cd
variant that take the target directory from stdin, it wouldn't have any effect when used in a pipeline in the Bourne shell, dash
and bash
to name a few. The last component of the command being run in a subshell, the change to a new directory won't affect the current shell. e.g.: echo /tmp | cd
would work with ksh93
but not bash
, dash
, zsh
, sh
, ...
cd <(echo /tmp)
would work with shells supporting process substitution (at least ksh
, bash
, zsh
) but wouldn't have any significant advantage compared to cd $(echo tmp)
The only use case that might be of interest would be something like:
echo tmp | (cd ; pwd)
Finally, such a variant would need to sort out the case it was given no argument but the expected behavior is to change the directory to the users's home or it was given no argument but the expected behavior is to read the name of the target directory from stdin. As there is no reliable way to decide, this is doomed.
Best Answer
It's the same as any other program. This allows you to redirect and pipe the I/O like other programs.
will execute the
cat filename
command whenbash
reads its standard input from the pipe.will execute the
echo foo
command, and the output will be redirected to the file.On Unix, there's nothing "special" about the shell. It's just an ordinary program whose primary purpose is executing other programs.