63

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

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • Why is that upvoted? Suppress any unwanted output with `2>/dev/null` and use `set -e` in scripts. – ott-- Mar 30 '15 at 00:43

3 Answers3

75

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.

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

devnull
  • 10,541
  • 2
  • 40
  • 50
  • 35
    Equivalent, but more readable for a casual user is to use `chmod -f 777 file.txt || true` – orion Mar 05 '14 at 11:03
  • 2
    @orion Depends. If one is familiar, then `:` seems equally readable. – devnull Mar 05 '14 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 04 '18 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 '18 at 19:49
8

I always loved

 chmod -f 777 file.txt || exit 0
Eran Chetzroni
  • 301
  • 3
  • 6
  • 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 '17 at 07:30