66

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 $?
  1

But from the example chmod return 1

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

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

3 Answers 3

77

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
  • 5
    I added this answer as an alternative to promote the practice writing readable code.
    – Gerry
    Mar 30, 2015 at 0:21
  • 3
    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, 2015 at 0:33
  • Thank you for that. I can't believe I messed that up. :) Edited with the correction.
    – Gerry
    Mar 30, 2015 at 1:58
65

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.

4
  • 36
    Equivalent, but more readable for a casual user is to use chmod -f 777 file.txt || true
    – orion
    Mar 5, 2014 at 11:03
  • 2
    @orion Depends. If one is familiar, then : seems equally readable.
    – devnull
    Mar 5, 2014 at 11:04
  • 3
    But if we write more readable code that the noobs can read, how will we keep our jobs?
    – Nick T
    Apr 4, 2018 at 22:15
  • 2
    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, 2018 at 19:49
9

I always loved

 chmod -f 777 file.txt || exit 0
1
  • 6
    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, 2017 at 7:30

You must log in to answer this question.