如果我有一个文件,我想让它成为世界可读的,但它位于多个目录的深处,而不是世界可执行的,我必须更改整个路径和文件的权限。
我可以这样做,chmod 755 -R /first/inaccessible/parent/dir
但这会更改路径目录中所有其他文件的权限,并使文件本身在我只想可读时可以执行。
有没有一种直接的方法可以在 bash 中做到这一点?
一种方法:
#! /bin/sh
fname=/full/path/to/file
dir=${fname%/*}
while [ x"$dir" != x ]; do
chmod 0755 "$dir"
dir=${dir%/*}
done
chmod 0644 "$fname"
Run Code Online (Sandbox Code Playgroud)
$ mkdir -p /tmp/lh/subdir1/subdir2/subdir3
$ touch /tmp/lh/subdir1/subdir2/subdir3/filehere
$ chmod -R 700 /tmp/lh
$ find /tmp/lh -ls
16 4 drwx------ 3 user group 4096 Oct 23 12:01 /tmp/lh
20 4 drwx------ 3 user group 4096 Oct 23 12:01 /tmp/lh/subdir1
21 4 drwx------ 3 user group 4096 Oct 23 12:01 /tmp/lh/subdir1/subdir2
22 4 drwx------ 2 user group 4096 Oct 23 12:01 /tmp/lh/subdir1/subdir2/subdir3
23 0 -rwx------ 1 user group 0 Oct 23 12:01 /tmp/lh/subdir1/subdir2/subdir3/filehere
Run Code Online (Sandbox Code Playgroud)
$ f=/tmp/lh/subdir1/subdir2/subdir3/filehere
Run Code Online (Sandbox Code Playgroud)
$ chmod o+r "$f"
$ (cd "$(dirname "$f")" && while [ "$PWD" != "/" ]; do chmod o+x .; cd ..; done)
chmod: changing permissions of `.': Operation not permitted
$ find /tmp/lh -ls
16 4 drwx-----x 3 user group 4096 Oct 23 12:01 /tmp/lh
20 4 drwx-----x 3 user group 4096 Oct 23 12:01 /tmp/lh/subdir1
21 4 drwx-----x 3 user group 4096 Oct 23 12:01 /tmp/lh/subdir1/subdir2
22 4 drwx-----x 2 user group 4096 Oct 23 12:01 /tmp/lh/subdir1/subdir2/subdir3
23 0 -rwx---r-- 1 user group 0 Oct 23 12:01 /tmp/lh/subdir1/subdir2/subdir3/filehere
Run Code Online (Sandbox Code Playgroud)
如果您确实希望中间目录也具有其他执行权限,只需将 chmod 命令更改为chmod o+rx
.
我从上面得到的错误消息是由于我的非 root 用户 ID 尝试更改/tmp
我不拥有的目录的权限而导致的。
该循环在子 shell 中运行,以将目录更改与当前 shell 的 $PWD 隔离。它通过输入包含该文件的目录开始循环,然后向上循环,沿途 chmod'ing,直到它到达根/
目录。循环在到达根目录时退出——它不会尝试 chmod 根目录。
您可以像这样创建一个脚本文件或函数:
function makeitreadable() (
chmod o+r "$1"
cd "$(dirname "$1")" &&
while [ "$PWD" != "/" ]
do
chmod o+x .
cd ..
done
)
Run Code Online (Sandbox Code Playgroud)