我试图编写一个脚本来规范 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 Archive
被 chmod
视为 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/