如何通过unix或shell脚本检查“root”是否拥有任何文件或目录?

时间:2018-03-28 14:42:23

标签: shell unix ls

我有一个目录。让我们的一天/data01。它有许多目录,子目录,文件等。我想检查目录及其所有子目录和文件,直到深度级别,它不归root所有。我想要一个命令或shell脚本,它可以保证深度/最后一级的任何子目录或文件不归root所有。我用以下命令检查 -

ls -lrt /data01/ 

ls -lrt /data01/* 

但是这种方式失败了(我不知道怎么回事)并且某些文件在交叉检查中由某人以root身份出现。需要帮助!

2 个答案:

答案 0 :(得分:4)

find /data01 -maxdepth $n -not -user root

使用find命令,上面的选项和参数都是非常自我解释的,只需要小心地将n分配到所需的深度。

如果要搜索到最后一级,只需删除-maxdepth $n即可。

如果您想探索更多功能,请使用man find

答案 1 :(得分:2)

选项1:

最简单,更好的选择是使用find,如下所示

find /data01 -not -user <user>           # Prints the out in console
find /data01 -not -user <user> > Output  # Redirect the output to file Output

注意:在您的案例中将<user>替换为root。如果要限制通过子目录的递归检查,请使用选项-maxdepth <levels>。根据手册的详细信息:在命令行参数下面的目录的最多级别(非负整数)下降

选项2:

如果您想使用ls,请与awk等其他命令结合使用,以实现此目的,如下所示,

ls -l * -R | awk '{if($3=="root") print $0}' 

# -R --> Recursively list through all sub directories
# if($3=="root") --> checks the 3rd position(owner user) in the ls output is "root",
# in your case use if($3!="root") , but you may need to grep out blank lines and directory names from the final output
# print $0 --> Prints the entire line when if block is true