[英]Bash - check if I have write permissions to parent of the any directory path
In my bash script I have to create bunch of directories (NOT files) - /opt/some/path1/
and /opt/some/path2/
and so on.在我的 bash 脚本中,我必须创建一堆目录(不是文件) - /opt/some/path1/
和/opt/some/path2/
等等。
Please note: In my case, /opt/some/
, the parent already exists, guaranteed.请注意:在我的情况下, /opt/some/
,父母已经存在,保证。 No validation required here.这里不需要验证。
How can I check if have write permissions to parent for my every mkdir /opt/some/path1/
and mkdir /opt/some/path2/
...?如何检查是否对我的每个mkdir /opt/some/path1/
和mkdir /opt/some/path2/
...具有写入权限?
I learned that we can use -w
for files so I tried this:我了解到我们可以将-w
用于文件,所以我尝试了这个:
if [ -w /opt/some/path1/ ]; then echo "You have directory creation permissions"; else echo "You are having a rough day.!"; fi
Which "obviously fails" miserably because the directory I am going to create (the path), does not exist yet.哪个“显然失败”很惨,因为我要创建的目录(路径)还不存在。
Is there a way we can use something similar to -w for files
for directories?有没有一种方法可以将similar to -w for files
? Or what I am missing here?或者我在这里缺少什么?
$ mkdir d1
$ [[ -w d1 ]] && echo Y
Y
$ mkdir d1/d11
$ chmod a-w d1
$ [[ ! -w d1 ]] && echo N
N
$ mkdir d1/d12
mkdir: d1/d12: Permission denied
you can check on a dir, which after all is a file你可以检查一个目录,它毕竟是一个文件
If I understand the question correctly, you want to check whether you have write access to the directory you want to create a subdirectory of, ie before creating /opt/some/path1/
you'd check write access to /opt/some/
.如果我正确理解了这个问题,您想检查您是否对要创建子目录的目录具有写访问权限,即在创建/opt/some/path1/
之前,您将检查对/opt/some/
的写访问权限。 You can do that by using the dirname
command to get the parent directory's path, then using the -w
test on that .您可以通过使用dirname
命令获取父目录的路径,然后使用-w
测试来做到这一点。 Note that mkdir
still might fail for reasons other than permissions on the parent directory, so you still need to check it for errors.请注意, mkdir
仍然可能由于父目录权限以外的原因而失败,因此您仍然需要检查它是否有错误。 Something like this:像这样的东西:
dirToCreate=/opt/some/path1/
if [ ! -w "$(dirname "$dirToCreate")" ]; then
echo "Insufficient permissions to create $dirToCreate" >&2
else
mkdir "$dirToCreate" || {
echo "Error creating $dirToCreate (due to something other than permissions)" >&2
}
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.