-1

I am practising and I am trying to:

1) create files with name of all combinations or r,w,x permission = 512 files;

2) change the permission of that file to match the name

I have created this script:

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

for i in *
   do
       syntax="${i//:}"
       u=${syntax:0:3}
       g=${syntax:3:3}
       o=${syntax:6:3}

       chmod u="$u",g="$g",o="$o" -- "$i" 
  done

It changed a few permissions to match the name, but not all what did I do wrong?

2 Answers 2

1

There are a few errors. First, you’re creating your files with commas between each set of three:

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

But then you’re removing colons. The colon should be a comma.

syntax="${i//:}"

This might cause trouble if the script is in the same directory:

for i in *

Of course if you’re running it as ../myscript or such, there’s no problem. But if the script is in the same directory, this will avoid it:

for i in ???????????

(Assuming you didn’t give it an 11-character name, of course.)

Finally, the big bug. You’re splitting the filename into three strings such as u='-w-' g='r-x' o='-wx'. These are the wrong syntax for chmod; you need to remove the hyphens first. So, after the split:

u=${u//-}
g=${g//-}
o=${o//-}

With all these changes, we arrive at this, which works:

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

for i in ???????????
    do
        syntax="${i//,}"
        u=${syntax:0:3}
        g=${syntax:3:3}
        o=${syntax:6:3}
        u=${u//-}
        g=${g//-}
        o=${o//-}

        chmod u="$u",g="$g",o="$o" -- "$i" 
    done
1

Your parsing is one letter wrong. In your parsing of syntax variable, you are getting for the string '--r,--r,--r': u='--r' g=',--' o='r,-'

You should change your script to:

   u=${syntax:0:3}
   g=${syntax:4:3}
   o=${syntax:8:3}

Also a tip, for debugging shell scripts try adding '-x' in your interpreter line. i.e '#!/bin/bash -x' Would give you a lot of great debug output :)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .