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

I need to set read and write permissions for root user to directory subfolderN and all its parent folders till root.

I can do it by hands:

$ sudo chmod +rx /root/subfolder1/subfolder2/subfolderN
$ sudo chmod +rx /root/subfolder1/subfolder2
$ sudo chmod +rx /root/subfolder1
$ sudo chmod +rx /root

But if N is big I am tired. How to do automatically by one command?

share|improve this question
up vote 13 down vote accepted

This can be done easily in the shell, starting in the subdir and moving upwards:

while [[ $f != "/" ]]; do chmod +rx $f; f=$(dirname $f); done;

This starts with whatever file/directory you set f too, and works on every parent directory, until it encounters "/" (or whatever you set the string in the condition of the loop to). It does not chmod "/".

share|improve this answer
Nice, I knew I was complicating things needlessly with Perl. – terdon Sep 14 '13 at 4:02

With csh, tcsh, ksh, zsh, bash or fish:

sudo chmod +rx /root{,/subfolder1{,/subfolder2{,/subfolderN}}}

With zsh:

until [[ $f = / ]] {chmod +rx $f; f=$f:h;}
share|improve this answer
Could you explain what the leading , in {,/subfolder} does? – terdon Sep 14 '13 at 14:28

Well, you could do something slightly more complex like:

echo "/root/subfolder1/subfolder2/subfolderN" | 
 perl -anF'/' -e 'while($#F>0){@b=join("/",@F);`chmod +rx @b`; pop @F}' 

To see what this will do, replace the chmod call with print:

$ echo "/root/subfolder1/subfolder2/subfolderN" | 
 perl -alnF'/' -e 'while($#F>0){@b=join("/",@F);print "chmod +rx @b"; pop @F}' 
chmod +rx /root/subfolder1/subfolder2/subfolderN
chmod +rx /root/subfolder1/subfolder2
chmod +rx /root/subfolder1
chmod +rx /root
share|improve this answer

I don't know what you are trying to do, but is better than you don't take the recursive lightly. That said, read the actual answer:

Umm... why not just use recursive.

sudo chmod -R +rx /root

Or if you don't like it, you can give chmod several directories:

sudo chamod +rx /root /root/subfolder1 /root/subfolder1/subfolder2 /root/subfolder1/subfolder2/subfolderN
share|improve this answer
That's not nearly the same operation, though. chmod -R /root changes everything under /root — including regular files and all directories. The question is about changing one chain of directories only. – 200_success Sep 14 '13 at 4:04
@200_success but that's not the only answer ;) – Braiam Sep 14 '13 at 4:08

Your Answer


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

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