If the variable string contains the path /a/b/c/d, the following instructions will change the permissions of /a, /a/b, /a/b/c and /a/b/c/d:
(
IFS=/
unset substring
for dir in $string; do
unset IFS
substring="$substring$dir/"
test "$substring" != "/" && chmod 755 "$substring"
done
)
How it works
The parentheses execute everything in a subshell, so changing the variables IFS and substring won't have any effect outside the subshell.
IFS=/ sets the internal file separator to slash, so the for loop will split $string at the slashes.
for dir in $string; do ... done will execute ... once for every component in $string.
In our example, $dir will take the values , a, b, c and d.
unset IFS changes the internal file separator back to default, since it will affect slashes in the directory paths.
substring="$substring$dir/" appends the current value of $dir to $substring.
In our example, $susbtring will take the values /, /a/, /a/b/, /a/b/c/ and /a/b/c/d/.
test "$substring" != "/" && chmod 755 "$substring" checks if the current value of $susbtring is different from /.
If it is, it sets the desired permissions.
a/b/calso change? Please give us an actual example and specify which parts of the string are always the same. – terdon Mar 19 at 19:07/a/b/c/d, you want to change the permissions of/a,/a/b,/a/b/cand/a/b/c/d? – Dennis Mar 19 at 19:10