如何检查不存在的当前用户的 linux 目录权限



我有一个应用程序,用户在其中输入一些路径,如果不存在,应用程序将使用该路径创建目录并添加日志文件。现在我想检查当前linux用户是否有权创建这个目录路径,以防它不存在。举个例子,假设/tmp/test是机器上存在的某个目录,用户输入/tmp/test/apps/log。如果这个目录不存在,我如何检查它的写入权限?我需要通过shell命令来完成它,这样我就可以自动化它。感谢

您需要检查是否有任何祖先目录是可写的,以及是否有任何东西会阻止创建。有很多角落的箱子,所以我可能忘了一些。

#!/bin/bash
# Syntax: can_mkdir_p [-f] <path>
#     -f   Succeed if the directory already exists and is writable
function can_mkdir_p() {
if [ "$1" == -f ]
then
exist_result=0
shift
else
exist_result=66
fi
dir="$1"
if [ -f "$dir" ]
then
# the requested path is an existing file, so mkdir is blocked.
return 65
elif [ -d "$dir" ]
then
# the requested path is an existing directory.
if [ -w "$dir" ]
then
# it is writable; if -f is supplied, it is okay
# otherwise, report that mkdir is blocked
return "$exist_result"
else
# the directory is not writable; report a permission problem
return 64
fi
fi
# if the path does not exist, check ancestor directories
while [ "$dir" != / ]
do
parent=$(dirname "$dir")
if [ -w "$parent" ]
then
# the parent is writable, so maybe we can mkdir -p
if [ -f "$dir" ]
then
# nope, a file already exists here that would block mkdir -p
return 65
elif [ -d "$dir" ]
then
# nope, a directory already exists here;
# if it was writeable, we would have reported okay
# in the previous iteration
return 64
else
# we found a writable ancestor that is not blocked, report okay
return 0
fi
fi
# this level is not okay, try one level up
dir="$parent"
done
# reached the root, still not okay
return 64
}
# example usage
if can_mkdir_p "$@"
then
echo Okay
else
case "$?" in
64)
echo "No write permission"
;;
65)
echo "Something is in the way"
;;
66)
echo "Already exists"
esac
fi

但正如我在评论中所说,你可以试着创建一个目录,如果失败了,就向用户投诉。这是大多数软件所做的。

相关内容

  • 没有找到相关文章

最新更新