I'd like to convert the Unix Permissions bits from octal to symbolic mode and viceversa. eg.:

$ mode-encode 'ugo+rwx'

$ mode-decode 0000

I know there are online permission bits calculators and chmod supports passing the bits in both ways, but i'd like a bash code snippet i can use with commands that does not support the symbolic mode.

EDIT: i'd like to get the permission bits, not the umask!

  • Note that for some values of the symbolic forms, the result will depend on the current umask. like for umask +r, or umask g=u (that one not supported by all implementation even though it's POSIX) Aug 29 '18 at 12:39
  • ugo+rwx gives 0000 by the way, not 0777 Aug 29 '18 at 12:41
  • 1
    Your latest edit makes it a bit confusing. Isn't @schily's answer what you want? If you want the complement, you can always do printf '%o\n' "$((value ^ 511))" Aug 30 '18 at 14:19
  • indeed i've noticed the results are inverted from what i expected (the previous examples were actually correct), so i had to add complement step to the @schily's answer
    – eadmaster
    Aug 30 '18 at 14:28
  • It's still unclear, all the a+x, go=u symbolic notations are relative, what do you want them to be relative to? Your question is now completely different from the original one which invalidates all the current answers. I'd suggest you revert this one to the original and post a separate question for your new requirements. Aug 30 '18 at 14:45

In any POSIX shell, you can call:

umask someval
umask -S  # outputs the symbolic form
umask     # outputs the octal form
umask -- "$savmask"

You could put this into a function

printmask() {
   savmask=$(umask) || return
   umask -- "$1" || return
   umask -S
   umask -- "$savmask"

Or use a subshell to avoid having to save and restore the umask:

printmask() (
  umask -- "${1?Please specify a umask}" || exit
  umask -S
  • ok, i've added umask 0777 at the beginning of the last printmask function to always have the full mask.
    – eadmaster
    Aug 29 '18 at 13:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.