Is it possible execute chmod and ignore error from command

Example ( remark file.txt not exsist to show the example )

When I type

chmod 777 file.txt

I get error on the output

  chmod: cannot access file.txt : no such file or directory

So I add the-f flag to the command as the following: ( file.txt not exist in order to show the case )

  chmod -f 777 file.txt
  echo $?

But from the example chmod return 1

Please advice how to force the chmod command to give exit code 0 in spite of error

  • Why is that upvoted? Suppress any unwanted output with 2>/dev/null and use set -e in scripts. – ott-- Mar 30 '15 at 0:43

Please advice how to force the chmod command to give exit code 0 in spite of error

chmod -f 777 file.txt || :

This would execute :, i.e. the null command, if chmod fails. Since the null command does nothing but always succeeds, you would see an exit code of 0.

  • 24
    Equivalent, but more readable for a casual user is to use chmod -f 777 file.txt || true – orion Mar 5 '14 at 11:03
  • 2
    @orion Depends. If one is familiar, then : seems equally readable. – devnull Mar 5 '14 at 11:04
  • 2
    But if we write more readable code that the noobs can read, how will we keep our jobs? – Nick T Apr 4 '18 at 22:15
  • 1
    chef developer here, just dropping some key words to help out others that have encountered the same issue I have. shell_out!(cmd+'|| true') is a lifesaver when you're trying to be idempotent with installations and need to ignore shell_out! compile errors. – JackChance Nov 13 '18 at 19:49

chmod -f 777 file.txt || true

As it's an OR, if one of the statements returns true, then the the return is true. This results in an exit status of zero.

  • 3
    I added this answer as an alternative to promote the practice writing readable code. – Gerry Mar 30 '15 at 0:21
  • 2
    The right branch of || won't get executed if chmod is successful... not that it makes much of a computational difference here. – dhag Mar 30 '15 at 0:33
  • Thank you for that. I can't believe I messed that up. :) Edited with the correction. – Gerry Mar 30 '15 at 1:58

I always loved

 chmod -f 777 file.txt || exit 0
  • 2
    This makes the script stop when chmod was unsuccessful. The question was to make the script continue running when there was a problem with it (ignore error). – Veda Jan 10 '17 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy