bash - 如何遍历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
现在,我如何遍历所有文件夹?
解决方案
使用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
推荐阅读
- java - 如何使用 Intellij IDEA 在 Java 中按类型和一个空格/制表符对齐变量?
- azure - Get-AzureADPolicy:无法识别术语“Get-AzureADPolicy”
- .net - TSQL CREATE ASSEMBLY FROM varbinary 破坏了 class_name 参数
- angular - ERROR 错误 TS2551:属性“帖子”不存在
- python - Pandas to_sql 不适用于 SQL Alchemy 连接
- bar-chart - 如何在 Qlik 上创建具有多列的堆叠条形图
- node.js - 在 ElectronJS/Angularapp 中连续运行循环而不阻塞渲染器
- ruby-on-rails - 为什么将 sass-rails gem 添加到我的 Gemfile
- apache-spark - 获取 Spark Dataframe 中特定单元格的值
- html - Firefox 忽略 html 的大小元素