首页 > 解决方案 > bash xargs 脚本中的“chmod:缺少操作数”

问题描述

我在 centos 7 中有一个文件夹,如下所示:

[root@localhost www]# ls -all
-rw-r--r--  1   apache websites     191 Apr 23  2018 robots.txt
drwxrwx---  3 websites websites      38 May 14  2018 functions

我想将这些文件夹和文件权限更改为:

[root@localhost www]# ls -all
-r--------  1   apache apache     191 Apr 23  2018 robots.txt
drx-------  3   apache apache      38 May 14  2018 functions

我尝试了如下的bash脚本:

find . -group websites -type f -print0 | tee >(xargs -0 chgrp apache) | xargs -0 chown apache | xargs -0 chmod 400
find . -group websites -type d -print0 | tee >(xargs -0 chgrp apache) | xargs -0 chown apache | xargs -0 chmod 500

但我得到错误:

chmod: missing operand after ‘400’
Try 'chmod --help' for more information.
chmod: missing operand after ‘500’
Try 'chmod --help' for more information.

有什么问题?提前致谢!

标签: bash

解决方案


为什么使用多个间接级别使事情复杂化,|以及tee何时可以对以下结果运行find循环

while IFS= read -r -d '' file; do
    chgrp apache "$file"
    chown apache "$file"
    chmod 400 "$file"
done < <(find . -group websites -type f -print0)

和目录如下

while IFS= read -r -d '' dir; do
    chgrp apache "$dir"
    chown apache "$dir"
    chmod 500 "$dir"
done < <(find . -group websites -type d -print0)

您可以通过引入一个条件来检查结果中的目录,从而很好地将其组合成一个find

while IFS= read -r -d '' content ; do
    chgrp apache "$content"
    chown apache "$content"
    [[ -d $content ]] && chmod 500 "$content" || chmod 400 "$content"
done < <(find . -group websites -print0)

至于您看到的错误,您tee的输出被xargs涉及消耗,chown除此之外它不可用,因为它不是tee最后一级的输出(在标准输出中可用)xargs。为了使其可用,请进行另一个级别的通行证

find . -group websites -type f -print0 | tee >(xargs -0 chgrp apache) | tee >(xargs -0 chown apache) | xargs -0 chmod 400

或者更好的是,只需使用xargs -0一次并在子 shell 中一次性运行一组命令

find . -group websites -type f -print0 | xargs -0 -I '{}' sh -c 'chgrp apache "{}"; chown apache "{}"; chmod 400 "{}"'

正如Charles Duffy在评论中所建议的那样,上述方法可能很容易受到攻击,因为我们将文件名替换为脚本文本,而不是在命令行上将它们作为单独的参数传递。该方法可以通过以下方式修改(他的建议)

find . -group websites -type f -print0 | xargs -0 sh -c 'for f; do chgrp apache "$f"; chown apache "$f"; chmod 400 "$f"; done' _

推荐阅读