Script to change Permissions on files and directories

Hey, It's me again.

Have a problem, that's not really a problem. I have the below script, that goes to the directory I want it to go to. lists out the directories available, lets you choose the directory you want, then it changes the permissions on said directory. using chmod -R and chown -R.

I however am setting chmod to 0770 recursively, but I want to be able to chose the directory, go into the directory, and determine if it's a file then chmod 0660, if directory 0770 and so on and so forth throughout the entire directory structure

I know i can test -f a file or test -d a directory. But cant work the logic out in my head to get what I want accomplished any help would be appreciated.

#!/bin/bash

source /generic/utils/etc/environments/perm.conf

cd $ENVR
DIRS=`ls -l $ENVR | egrep '^d' | awk '{print $9}'`

for DIR in "${DIRS[@]}";
do
    echo "$DIR"
        echo "Which environment do you want?: "
        echo -n "> "
        read i
echo "Changing permissions now..."

sudo chown -R $OWN:$GRP "$i" && sudo chmod -R $MOD1 "$i"
#cd $ENVR/$i
#sudo chmod -R $MOD2 *

echo "Permissions are changed!"

done

Perhaps the following replacement for your script will give you a template showing how you can attack your problem:

#!/bin/bash
source /generic/utils/etc/environments/perm.conf
find $ENVR \( -type f -exec echo chmod 0660 {} + \) -o \( -type d -exec echo chmod 0770 {} + \)
1 Like

What do you mean by "environment"?
Maybe the following code snippet can help. In this example, I'm passing a certain file or directory as argument. You can later change that to better suit your needs (insert the modified code right after the line where it says Changing permissions now... :

#!/bin/bash
if [ -f $1 ]; then
    sudo chown owner:group $1
    chmod 660 $1
elif [ -d $1 ]; then
    sudo chown -R owner:group $1
    chmod -R 770 $1
fi

Then, after the for loop is over, I'd add the confirmation message:

if [ $? -eq 0 ]; then
    echo "Permissions were changed successfully."
fi

Hope it helps.

1 Like