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
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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
$? 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
cat my-file.txt 2>&- || false