Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
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
up vote 14 down vote accepted

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.

share|improve this answer
Equivalent, but more readable for a casual user is to use chmod -f 777 file.txt || true – orion Mar 5 '14 at 11:03
@orion Depends. If one is familiar, then : seems equally readable. – devnull Mar 5 '14 at 11:04

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.

share|improve this answer
I added this answer as an alternative to promote the practice writing readable code. – Gerry Mar 30 '15 at 0:21
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
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.