首页 > 解决方案 > 如何遍历bash中的所有文件夹和子文件夹?

问题描述

我试图遍历父文件夹中的所有文件夹,以更改每个文件和文件夹的所有权,前提是它由 bash 脚本的 root 拥有。

我当前的代码只能完成 1 次迭代,如下所示:

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

现在,我如何遍历所有文件夹?

标签: bashshellloops

解决方案


使用find,

  • 要仅过滤 root 拥有的文件,请使用-user root
  • 要将文件的所有者更改为特定用户,请使用-exec chown NEWUSER '{}' \;

例子:

前:

# 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

如果当前所有者是 root,则更改所有者的命令:

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

后:

# 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

推荐阅读