I need to get the contents of a file but want to prevent an error if it does not exist.
Is it possible to do something like this?
cat my-file.txt || false
I need to get the contents of a file but want to prevent an error if it does not exist.
Is it possible to do something like this?
cat my-file.txt || false
You have a few options
Avoid printing the file unless it exists, but still allow cat to complain if the file exists but cannot be opened
[ -f my-file.txt ] && cat my-file.txt
Avoid printing the error message generated if the file cannot be opened for whatever reason, by redirecting stderr to "nowhere"
cat my-file.txt 2>/dev/null
Avoid setting $? to a non-zero exit status, which would indicate that an error occurred.
cat my-file.txt || true
In the first two cases, the next command can be a status test to check if the cat was successful. For example
cat my-file.txt 2>/dev/null
[ $? -ne 0 ] && echo 'There was an error accessing my-file.txt'
Further, this can then be wrapped into a more readable conditional, like this
if ! cat my-file.txt 2>/dev/null
then
echo 'There was an error accessing my-file.txt'
fi
In the last case, there is no point in using the command in an if statement, as it's successfully hides the exit status of cat in such a way that the exit status of the compound command is always zero (it "prevents the error", in a way).
Close stderr with 2>&-:
cat my-file.txt 2>&- || false
U&L: Difference between 2>&-, 2>/dev/null, |&, &>/dev/null and >/dev/null 2>&1
cat my-file.txt 2>/dev/nullsuppresses the error output or[ -f my-file.txt ] && cat my-file.txtskips thecatif the file is not present or, if you want atrueexit status, use[ ! -f my-file.txt ] || cat my-file.txt– Bodo Dec 28 '20 at 12:42cat, the fact that the exit status of your pipeline is non-zero, or do you want to preventcatfrom even try to process an non-existent file? – Kusalananda Dec 28 '20 at 12:46