22

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
7

2 Answers 2

30
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 < 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.

20

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". 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).

4
  • 18
    No. in 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). Nov 24, 2016 at 11:19
  • Cool! Pure logic. I'll edit my nonsense. Nov 24, 2016 at 11:34
  • @StéphaneChazelas Hello, why is it better to use the redirection operator wherever possible? Jan 25, 2020 at 18:41
  • @FuRinKaZan_001, it is not necessarily always better, but there are several advantages in most cases where it's possible. See for instance When should I use input redirection? Jan 25, 2020 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.