歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> stat用法:獲取文件對應權限的數字

stat用法:獲取文件對應權限的數字

日期:2017/2/28 13:56:34   编辑:Linux教程

題目:文件屬性為-rw-r--r-- 對應權限為644,如何使用命令獲取權限對應的數字??

舉例如下:

[linuxidc@localhost ~]$ ll -l
-rw-r--r-- 1 linuxidc wheel 38 Oct 12 16:29 1.txt

使用stat命令可以查看
[linuxidc@localhost ~]$ stat 1.txt
File: `1.txt'
Size: 38 Blocks: 8 IO Block: 4096 regular file
Device: fd00h/64768d Inode: 390954 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 503/ linuxidc) Gid: ( 10/ wheel)
Access: 2015-10-12 16:29:34.674990005 +0800
Modify: 2015-10-12 16:29:32.248990536 +0800
Change: 2015-10-12 16:29:32.248990536 +0800

取出對應的數字則需要使用正則sed awk 或cut ,head,tail命令;

方法1:使用正則或命令取
head,tail,cut

[linuxidc@localhost ~]$ stat 1.txt |head -n4|tail -n1|cut -d "/" -f1|cut -d "(" -f2
0644


sed,cut

[linuxidc@localhost ~]$ stat 1.txt |sed -n '4p'|cut -d "/" -f1|cut -d "(" -f2
0644

sed,awk

[linuxidc@localhost ~]$ stat 1.txt |sed -n '4p'|awk -F"/" '{print $1}'|awk -F"(" '{print $2}'
0644

方法2:stat -c 命令

[linuxidc@localhost ~]$ stat -c %a 1.txt
644

注意:如何想到法二的思考過程,比答題更重要。當命令結果包含我們需要的內容的時候,我們要想到是否有具體的參數能夠一步達到我們需要的結果。

man stat 查看幫助
-c --format=FORMAT
use the specified FORMAT instead of the default; output a new line after each use of FORMAT
使用特殊格式代替默認輸出;
常用的參數有如下:
%a Access rights in octal 8進制顯示訪問權限,0644
%A Access rights in human readable form 以人類可讀的形式輸出,
%F File type 文件的類型
%g Group ID of owner 所屬組gid的號碼
%G Group name of owner 所屬組的名稱
%h Number of hard links 硬連接的數量
%i Inode number inode的值
%n File name 文件名
%o I/O block size IO塊大小
%s Total size, in bytes 文件的總大小,字節顯示;
%u User ID of owner 所屬主的uid號碼
%U User name of owner 所屬主的名稱
%x Time of last access 最後訪問的時間
%X Time of last access as seconds since Epoch 最後訪問時間的時間戳
%y Time of last modification 最後修改的時間
%Y Time of last modification as seconds since Epoch 最後修改時間的時間戳
%z Time of last change 最後更改的時間
%Z Time of last change as seconds since Epoch 最後更改的時間的時間戳

使用參數結果如下:
[linuxidc@localhost ~]$ ls -l 1.txt
-rw-r--r-- 1 linuxidc wheel 38 Oct 12 16:29 1.txt
[linuxidc@localhost ~]$ stat -c %a 1.txt
644
[linuxidc@localhost ~]$ stat -c %A 1.txt
-rw-r--r--
[linuxidc@localhost ~]$ stat -c %b 1.txt
8
[linuxidc@localhost ~]$ stat -c %B 1.txt
512
[linuxidc@localhost ~]$ stat -c %d 1.txt
64768
[linuxidc@localhost ~]$ stat -c %F 1.txt
regular file
[linuxidc@localhost ~]$ stat -c %g 1.txt
10
[linuxidc@localhost ~]$ stat -c %G 1.txt
wheel
[linuxidc@localhost ~]$ stat -c %u 1.txt
503
[linuxidc@localhost ~]$ stat -c %U 1.txt
linuxidc
[baby@localhost ~]$ stat -c %h 1.txt
1
[linuxidc@localhost ~]$ stat -c %i 1.txt
390954
[linuxidc@localhost ~]$ stat -c %n 1.txt
1.txt
[linuxidc@localhost ~]$ stat -c %o 1.txt
4096
[linuxidc@localhost ~]$ stat -c %s 1.txt
38

Copyright © Linux教程網 All Rights Reserved