Javier Valencia
Javier Valencia

Reputation: 695

mkdir recursion with permissions

It's a simple question, I'm writing a bash script called from cron grouping files in tar file and classifing into a dir structure.

These dir needs a special owner and permissions, and I call mkdir command thru su:

#!/bin/bash

... # shortened code

$PERMS=750
$DIR=/home/luser/0/01/012/0123
$OWNER=luser

... # shortened code

su -c "mkdir -m $PERMS -p $DIR" $OWNER

Output for ll -R /home/luser/0

/home/luser/0:
total 4
drwxr-xr-x 3 luser luser 4096 Jan  7 18:13 01

/home/luser/0/01:
total 4
drwxr-xr-x 3 luser luser 4096 Jan  7 18:13 012

/home/luser/0/01/012:
total 4
drwxr-x--- 2 luser luser 4096 Jan  7 18:13 0123

/home/luser/0/01/012/0123:
total 0

Only the deepest dir has permissions (750) setting rightly.

I don't know how deep it's the last directory and set permissions for all home's file it's too hard (too much files).

PS: I'm googled about that, but I find nothing.

Upvotes: 1

Views: 1765

Answers (1)

Dark Falcon
Dark Falcon

Reputation: 44201

You can restrict the permissions on the parent directories via umask. Here is an example:

PERMS=750
UMASK=$(echo "$PERMS" | tr "01234567" "76543210")
DIR=/home/luser/0/01/012/0123
OWNER=luser

su -c "umask $UMASK; mkdir -m $PERMS -p $DIR" $OWNER

In action:

> PERMS=750
> UMASK=$(echo "$PERMS" | tr "01234567" "76543210")
> (umask $UMASK; mkdir -m $PERMS -p 1/2/3/4)
> ll -R .
.:
drwxr-x---  3 luser luser  4096 Jan  7 1:38 1/

./1:
drwxr-x--- 3 luser luser 4096 Jan  7 1:38 2/

./1/2:
drwxr-x--- 3 luser luser 4096 Jan  7 1:38 3/

./1/2/3:
drwxr-x--- 2 luser luser 4096 Jan  7 1:38 4/

Upvotes: 3

Related Questions