3

I created 512 files, with names made from combinations of permisions (r, w, x).

I created them like this:

touch ./{r,-}{w,-}{x,-}{r,-}{w,-}{x,-}{r,-}{w,-}{x,-}

and I want the files to have same permisions as their name indicates, for example, files r-x--xrwx should have permissions r-x--xrwx.

I tried to do it like this:

for i in *
do
    u=${i:0:3};g=${i:3:3};o=${i:6:3}
    chmod u=$u,g=$g,o=$o -- $i
done

Some of the files end up with the correct permissions, but, for others, permissions don't match the name. How can I fix this?

5

The parameters you're passing to chmod include - symbols but shouldn't. To fix that, remove the - symbols:

for i in *
do
  u=${i:0:3};g=${i:3:3};o=${i:6:3};
  u=${u//-/};g=${g//-/};o=${o//-/};
  chmod -- "u=$u,g=$g,o=$o" "$i"
done
0

You may convert the names into an octal number (e.g. 744) and use it to change permissions:

#!/bin/bash
# touch ./{r,-}{w,-}{x,-}{r,-}{w,-}{x,-}{r,-}{w,-}{x,-}

for filename in *
do
    str="$filename"
    str="${str//-/0}"
    str="${str//[^0]/1}"
    dec="$((2#$str+0))"
    oct="$(printf '%03o' "$dec")"
    #echo "$str $dec $oct : "
    chmod -- "$oct" "$filename"
done

The octal number is obtained by:

  • change each - to a zero 0, each any other letter by a one 1.
  • convert the binary number to a decimal (because the shell understand only decimal).
  • convert the decimal number into octal.
  • use the octal number to change permissions.

The -- in the chmod command is because filenames with several dash - are confusing to the command, it believes that the filename is an option.

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.