2013-10-24 19 views
5

我需要测试一个bash脚本,如果一个给定的用户可以阅读一个给定的目录里面的所有文件和子目录。该脚本运行为Bash脚本来测试给定的用户是否可以读取目录和里面的所有文件?

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

 
su -m $user -c "test -r $dir && test -x $dir" 
if [ $? -ne ]; then 
    echo "$dir is not readable or executable" 
fi 

你会建议纠正或改进呢?

回答

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 \) 
+0

它看起来像“发现”返回0,即使某些文件无法读取。如何测试$ dir内的_all_文件是否可以被$ user读取? – Michael

+0

@Michael请参阅上面的编辑。 – devnull

+0

谢谢。它现在工作。 – Michael

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是OK在这种情况下,它仍然值得进入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" 
    
+0

谢谢!这是一个很好的学习答案 – Michael

相关问题