Both of the following commands try to open a non-existing file foo
, but the error messages are a little different. What could be the reason?
$ cat foo
cat: cannot open foo
$ cat < foo
-bash: foo: No such file or directory
cat foo
This runs the cat
command with argument foo
. The error printed onscreen depends entirely on what was decided by the programmer of the command cat
.
cat < foo
This feeds the contents of the file foo
to the cat
command by using the Bash stdin redirection. If the file doesn't exist, it is Bash that complains about it, not cat
.
In $ cat foo
the shell (here bash) executes the cat
command and passes the parameter foo
. The cat program chooses to interpret that parameter as a file name - and tries to open the file.
The error you see is from the cat program which (naturally) cannot open the file.
The version $ cat < foo
is a redirection which is handled by the shell. <
is a shell operator which instructs the shell to open a file and redirect it to stdin. The file does not exist so you get a "No such file" and cat
is not even run. This time the error comes from the shell (bash) and looks a little different.
This is why you see 2 different errors. The cause is the same - but it is from 2 different programs (cat and bash).
cat < foo
, cat
is not invoked if the redirection fails. That (and having consistent error message) is one reason why it's often better to use redirection where possible. Also consider the cat < in > out
vs cat in > out
where the former prevents out
to be overridden if in
doesn't exist (the shell cancels the command right after the failing < in
redirection and doesn't do the next > out
redirection, let alone invoke cat
).
Commented
Nov 24, 2016 at 11:19
cat
. Now, I wonder where the second message comes from, considering that it starts withbash:
...