linux - 我似乎无法在 bash 脚本中传递带有空格的参数

标签 linux bash find chmod

我试图编写一个脚本来规范 Linux 中的权限:

for f in $(find . -type f); do
    file "$f" | grep -e "ELF 64-bit LSB executable" -e "ELF 32-bit MSB executable" > /dev/null
    if [ $? = 0 ]; then
        chmod -c u=rwx,g=rx,o=rx "$f"
    else
        chmod -c u=rw,g=r,o=r "$f"
    fi;
done

显然,我正在尝试将文件路径传递给 chmod我使用双引号,如"$f"但不知何故仍然得到 No such file or directory错误:

chmod: './FreeDesktop_integration/nautilus-scripts/Archiving/PeaZip/Extract''e erişilemedi: Böyle bir dosya ya da dizin yok
chmod: 'Archive''e erişilemedi: Böyle bir dosya ya da dizin yok

看来./FreeDesktop_integration/nautilus-scripts/Archiving/PeaZip/Extract Archivechmod 视为 2 个文件(这是相当出乎意料的)。

那么是什么导致了这个问题以及如何解决这个问题(正确传递参数)?

额外问题:是否有更好的方法来实现我想要通过脚本实现的目标?

最佳答案

for f in $(find .-type f)中, shell 对 find 命令的输出执行分词。 这样一来,像您一样使用它就不安全了。

您可以通过使用 while 循环来确保安全:

find . -type f -print0 | while IFS= read -r -d '' f; do
    if file "$f" | grep -qe "ELF 64-bit LSB executable" -e "ELF 32-bit MSB executable"; then
        chmod -c u=rwx,g=rx,o=rx "$f"
    else
        chmod -c u=rw,g=r,o=r "$f"
    fi
done

(我还稍微简化了条件,以及 @CharlesDuffy 中的一些提示。)

关于linux - 我似乎无法在 bash 脚本中传递带有空格的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47211255/

相关文章:

linux - grep 遍历数千个 gz 文件的最快方法?

linux - 如何在 Bash/Debian 中获取文件创建日期/时间?

linux - 较新版本的 Linux 是否使用与 libata-core.h 不同的包含?

linux - Wine32 Kali Linux错误

bash - 如何在匹配正则表达式的第一行之后获取文件的一部分

linux - 遇到 "find:/data/cdr/cdr-ivr.log: No such file or directory"后 Bash 脚本退出

python - 在列表中搜索字符或字符串(如网站上的查找功能)

regex - 如何使用Linux命令工具去除字符串开头和结尾的数字?

Bash $0 与终端使用的命令不匹配

linux - 从文件内部删除模式条目