Bash – How to suppress file redirection errors

bash

With cat, I am able to hide the "No such file or directory" error like so:

cat file.txt 2>/dev/null

However, this shows the error

< file.txt 2>/dev/null
bash: file.txt: No such file or directory

How can I print the file contents if the file is found, but hide errors if it is not?

Note: I am making the intentional effort to avoid the use of the cat command: https://stackoverflow.com/questions/11710552/useless-use-of-cat

Best Answer

Just change the order and do the redirection of stderr to /dev/null FIRST:

%% <file.txt 2>/dev/null
bash: file.txt: No such file or directory
%% 2>/dev/null <file.txt
%%

Keep in mind that redirections are always performed from left to right; the idea is to have the stderr already redicted when the failing redirection is performed.


However, AFAIK, only zsh allows you to use just <file as an equivalent of cat file (or more file, subject to its NULLCMD and READNULLCMD options).

While bash and some other shells deceptively support $(<file) as a special form of command substitution, they only support that exact form, nothing more:

bash% echo text > file
bash% <file
bash% echo $(<file)
text
bash% echo $(<file;<file)

bash%

While in zsh:

zsh$ <file
text
zsh$ <file >out
zsh$ <out
text
zsh$ echo $(<file;<file)
text text