0

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
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
clarkk
  • 1,837
  • do you mean you don't want error to be outputed to screen? just output stderr to /dev/null – ralz Dec 28 '20 at 12:40
  • cat my-file.txt 2>/dev/null suppresses the error output or [ -f my-file.txt ] && cat my-file.txt skips the cat if the file is not present or, if you want a true exit status, use [ ! -f my-file.txt ] || cat my-file.txt – Bodo Dec 28 '20 at 12:42
  • 2
    Consider updating your question with an explanation of what you mean by "preventing an error". It's unclear what error you want to prevent. Is it the diagnostic message produced by cat, the fact that the exit status of your pipeline is non-zero, or do you want to prevent cat from even try to process an non-existent file? – Kusalananda Dec 28 '20 at 12:46

2 Answers2

5

You have a few options

  1. 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
    
  2. 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
    
  3. 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).

Kusalananda
  • 333,661
Chris Davies
  • 116,213
  • 16
  • 160
  • 287
-1

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

GAD3R
  • 66,769