确认用户对当前目录具有读写权限

确认用户对当前目录具有读写权限

我正在编写一个脚本,该脚本需要创建文件和目录,但在执行此操作之前,我想运行检查以查看运行该脚本的用户是否具有读写权限。如果是,则脚本应继续,否则应告诉用户他们需要尝试在其他目录中运行该脚本。

答案1

通过test命令:

# doesn't  echo OK, because no read-write permissions
$ [ -r /proc/28127/task/28189/fd ] && [ -w /proc/28127/task/28189/fd  ] && echo "OK" 
# echoes OK, because my user has read-write permissions to the directory
$ [ -r $HOME ] && [ -w $HOME  ] && echo "OK"                                                          
OK

可以将其放入函数中并将其存储到脚本中~/.bashrc或在脚本中使用:

check_dir() {
    [ -r "$1" ] && [ -w "$1" ] && echo "OK" 
} 

用法如下:

$ check_dir $HOME
OK

通过find命令:

# Doesn't return directory name because I don't have read/write permissions
$ find /proc/28127/task/28189/fd -maxdepth 0 -readable -writable                                      

# Returns  directory name, because I can write/read there
$ find $HOME  -maxdepth 0 -readable -writable                                                         
/home/xieerq

相关内容