user13754206
user13754206

Reputation: 11

how to iterate through all folders and subfolders in bash?

I am trying to iterate through all folders inside the parent folder to change the ownership of every files and folder only if it is own by root from bash script.

my current code can only accomplish the 1 iteration which look something like this below:

filenames=$(ls | awk '{print $1}')


for i in $filenames
do
    if [ -d $i ]
    then
        ownership1=$(ls -ld $i | awk '{print $3}')
        if [ "$ownership1" == "root" ]
        then
            sudo chown anotheruser $i
        else
            echo "not own by root"
        fi

        ownership2=$(ls -ld $i | awk '{print $4}')
        if [ "$ownership2" == "root" ]
        then
            sudo chgrp anotheruser $i
        else
            echo "not own by root"
        fi
        


    else
        ownership3=$(ls -la $i | awk '{print $3}')
        if [ "$ownership3" == "root" ]
        then
            sudo chown anotheruser $i
        else
            echo "not own by root"
        fi


        ownership4=$(ls -la $i | awk '{print $4}')
        if [ "$ownership4" == "root" ]
        then
            sudo chgrp anotheruser $i
        else
            echo "not own by root"
        fi
    fi


done

Now,how do i iterate through all the folders ?

Upvotes: 1

Views: 448

Answers (1)

Kristian
Kristian

Reputation: 2505

Use find,

  • to filter only file owned by root, use -user root
  • to change the file's owner to specific user, use -exec chown NEWUSER '{}' \;

Example:

before:

# ls -alR
.:
total 0
drwxr-xr-x  3 root     root 140 Oct  6 15:44 .
drwxrwxrwt 21 root     root 680 Oct  6 15:43 ..
-rw-r--r--  1 kristian root   0 Oct  6 15:43 a
-rw-r--r--  1 guest    root   0 Oct  6 15:43 b
-rw-r--r--  1 root     root   0 Oct  6 15:43 c
-rw-r--r--  1 root     root   0 Oct  6 15:43 d
drwxr-xr-x  2 root     root 120 Oct  6 15:44 e

./e:
total 0
drwxr-xr-x 2 root     root 120 Oct  6 15:44 .
drwxr-xr-x 3 root     root 140 Oct  6 15:44 ..
-rw-r--r-- 1 kristian root   0 Oct  6 15:44 a
-rw-r--r-- 1 guest    root   0 Oct  6 15:44 b
-rw-r--r-- 1 root     root   0 Oct  6 15:44 c
-rw-r--r-- 1 root     root   0 Oct  6 15:44 d

Command to change owner if the current owner is root:

find . -user root -exec chown http '{}' \;

After:

# ls -alR
.:
total 0
drwxr-xr-x  3 http     root 140 Oct  6 15:44 .
drwxrwxrwt 21 root     root 680 Oct  6 15:43 ..
-rw-r--r--  1 kristian root   0 Oct  6 15:43 a
-rw-r--r--  1 guest    root   0 Oct  6 15:43 b
-rw-r--r--  1 http     root   0 Oct  6 15:43 c
-rw-r--r--  1 http     root   0 Oct  6 15:43 d
drwxr-xr-x  2 http     root 120 Oct  6 15:44 e

./e:
total 0
drwxr-xr-x 2 http     root 120 Oct  6 15:44 .
drwxr-xr-x 3 http     root 140 Oct  6 15:44 ..
-rw-r--r-- 1 kristian root   0 Oct  6 15:44 a
-rw-r--r-- 1 guest    root   0 Oct  6 15:44 b
-rw-r--r-- 1 http     root   0 Oct  6 15:44 c
-rw-r--r-- 1 http     root   0 Oct  6 15:44 d

Upvotes: 1

Related Questions