How can I print the file contents if the file is found, but hide errors if it is not?
Test if the file exists first?
if [ -f "$file" ]; then
cat "$file" # or whatever it is you're running
fi
or if it's readable
if [ -r "$file" ]; then ...
Both of those suffer from a TOCTTOU (time-of-check to time-of-use) vulnerability, in that the file could be removed or its permissions changed just after the test, before cat
runs. That would probably give you an error anyway. Similarly, some odd device file or such might appear to be readable, but still give an error when read.
If there's a pipeline you're running, you might as well put the cat
there to read the file. That way, the timing issue would not exist:
cat "$file" 2>/dev/null | whatever...
I know you didn't ask for this, but the cat
is not useless here. It's being used to separate the errors from reading $file
from whatever other errors the right-hand side of the pipeline might produce.
cat
to print anything, but since redirections are processed L to R maybe just2>/dev/null cat < file.txt
or even2>/dev/null < file.txt cat
– steeldriver Feb 17 '20 at 23:04cat
is only (arguably) useless when there's another process in your pipeline that is capable of reading your input directly. I don't think that's the case here? – steeldriver Feb 17 '20 at 23:50