6

如果给定用户可以读取包含所有文件和子目录的给定目录,我需要在 bash 脚本中进行测试。该脚本以root身份运行。

假设给定的用户名是$user并且要测试的目录是$dir我在脚本中添加了以下行

su -m $user -c "test -r $dir && test -x $dir"
如果 [ $? -ne]; 然后
   echo "$dir 不可读或不可执行"
菲

您会建议纠正或改进它吗?

4

2 回答 2

4

你可以简单地说:

su -m $user -c "find $dir >/dev/null 2>&1 || echo $dir is not readable or executable"

如果其中的任何文件/目录不可读,这将生成不可读或可执行$dir消息。

find $dir如果无法读取任何文件,将返回非零错误代码。


编辑:查找所有不可读的目录/文件的更完整(或更可靠)的方法是:

find . \( -type d -perm /u+r -o -type d -perm /u+x -o -type f -perm /u+r \)
于 2013-10-24T14:55:32.423 回答
4
  1. 这里似乎缺少一些东西:

    if [ $? -ne ]; then
    

    你肯定是想写:

    if [ $? -ne 0 ]; then
    

    但实际上测试不是必需的,因为您可以使用||

    su -m $user -c "test -r $dir && test -x $dir" ||
    echo "$dir is not readable or executable"
    
  2. 代替:

    test -r $dir && test -x $dir
    

    您可以使用-a选项(逻辑与)来test

    test -r $dir -a -x $dir
    
  3. 变量$user从何而来?它值得信赖吗?如果没有,如果有人提供像root;. 即使您$user确定在这种情况下没问题,仍然值得养成在 shell 脚本中引用变量的习惯:在这里,如果您编写以下代码,您将是安全的:

    su -m "$user" -c "..."
    
  4. 如果$dir是不受信任的,也会出现类似的问题——有人可能会提供类似/; sh. 但在这种情况下,像这样引用它是行不通的:

    su -m "$user" -c "test -r '$dir' -a -x '$dir'"
    

    因为有人可能会提供像/'; sh; echo '. 相反,您需要将引用"$dir"的内容作为参数传递给子shell,然后您可以安全地使用$1

    su -m "$user" -c 'test -r "$1" -a -x "$1"' -- "$dir"
    
于 2013-10-24T15:42:15.560 回答