Search code examples
bashmkdir

create hierarchy of folders, and set permissions


mkdir has options:

  • -p that creates all parent directories if missing
  • -m which changes user rights.

Problem for me is, that -m 755 is applied only to the leaf directory.

mkdir -m 755 -p a/b/c -> c has mode 755 but a and a/b have modes 700. (I want a and a/b to be also 755)

Is there easy solution? (or just iterate over parents and chmod each?)


Solution

  • That is a bit unexpected behaviour from mkdir, I would also assume the -m flag would have effect on all created directories, not just the leaf node.

    I see two easy ways to do this:

    1. $ (umask 022; mkdir -p a/b/c)
    2. $ install -d -m 755 a/b/c

    The umask controls all file creation done by the shell and is a mask of the permission bits set (this makes the values a bit hard to use). Putting the two commands in parenthesis means it will only have effect for that sub shell.

    Using the install tool is another option. With the -d option, it behaves the same way as mkdir -p, but the -m flag will be used for all directories, not just the leaf node. install is part of the coreutils package, and will most likely be available on any system.