? 閱讀時長:10 分鐘
?? 面向人群:Linux用戶
?? 適用場景:需要查詢單個或多個文件or目錄的權(quán)限
1.背景
了解文件所賦予的權(quán)限對自己工作開展很重要绑谣;
大多數(shù)情況只查看可讀權(quán)限键痛,自己用鼠標雙擊就可以檢查消恍。但有時候雙擊打不開可能是數(shù)據(jù)損壞,不一定是權(quán)限問題解滓。
- 如果用Linux來看穗酥,一般都知道使用ls -l 來查看文件或目錄的權(quán)限瞬浓,但只能查閱所有者、所屬組机打、其他人分別有哪些權(quán)限矫户。
但對于你來說 看不出自己對這個文件是否有rwx權(quán)限。
-rwxrwx---+ 1xxx xxx 655360 Jun 26 15:11 test.sas7bdat
我們知道上面文件所屬組權(quán)限是rwx,另一個思路是查看自己是否在所屬組里面残邀,可以看權(quán)限但不夠直觀皆辽。groups/getfacl
目前好像沒提供查詢個人對特定文件或目錄權(quán)限命令柑蛇,間接的方法也不太方便。
?2.Usage
已經(jīng)加載到env_setting里面驱闷,重新打開MobaXterm tab或source ~/.bashrc 即可使用耻台;
$ check_permission <dirname_or_filename>
Step1: 進入指定的Folder下面
$ cdwin "Z:\xxx\current"
Step2: 查看幫助信息及運行
$ check_permission -h
Usage:
cdwin "Z:\xxx\current"
check_permission ae.sas7bdat
$ check_permission
filename or dirname does not exist.
$ check_permission ae.sas7bdat
ae.sas7bdat has read permission.
ae.sas7bdat has write permission.
ae.sas7bdat has execute permission.</pre>
3.代碼邏輯
- 使用Shell腳本里面-e/-r/-w/-x 進行邏輯判斷,確定特定的目錄及文件是否有對應的權(quán)限空另;
Code
#盆耽!/bin/bash
####################################### check_permission ##########################################
function check_permission(){
file_or_dir=$1
## 判斷參數(shù)是否為空
if [[ "$file_or_dir" = "--help" ]] || [[ "$file_or_dir" = "-h" ]]; then
echo "Usage: "
echo 'cdwin "Z:\xxx\current" '
echo 'check_permission ae.sas7bdat'
return 1
fi
# 判斷目錄或文件是否存在
if [ ! -e "$file_or_dir" ];then
echo "filename or dirname does not exist."
return 1
fi
# 判斷是否有讀權(quán)限
if [ -r "$file_or_dir" ];then
echo "$file_or_dir has read permission."
else
echo "$file_or_dir does not have read permission."
fi
# 判斷是否有寫權(quán)限
if [ -w "$file_or_dir" ];then
echo "$file_or_dir has write permission."
else
echo "$file_or_dir does not have write permission."
fi
# 判斷是否有執(zhí)行權(quán)限
if [ -x "$file_or_dir" ]; then
echo "$file_or_dir has execute permission."
else
echo "$file_or_dir does not have execute permission."
fi
}</pre>
# 4.Notes:
* 只支持單個文件或目錄權(quán)限查詢,如果需要批量查詢可以使用循環(huán)(可優(yōu)化)扼菠。如下:
### 查看全部權(quán)限列表
$ cdwin "Z:\xxx\current"
$ ls | while read id; do check_permission $id; done;
aecm.sas7bdat has read permission.
aecm.sas7bdat has write permission.
aecm.sas7bdat has execute permission.
ae.sas7bdat has read permission.
ae.sas7bdat has write permission.
ae.sas7bdat has execute permission.
### 查看目錄下沒有可讀權(quán)限的文件
$ cdwin "Z:\xxx\current"
$ ls | while read id; do check_permission $id | grep "does not have read permission" ;done
??歡迎評論交流~