說明:本文爲老男孩linux培訓某節課前考試試題及答案分享博文內容的一部分,也是獨立成題的,你能夠點下面地址查看所有的內容信息。
http://oldboy.blog.51cto.com/2561410/791245
答題的思惟比作題自己更重要,就是老男孩如何想到的解決問題的思路。
node
1.如何取得/etiantian文件的權限對應的數字內容,如-rw-r--r-- 爲644,要求使用命令取得644這樣的數字。
解答:ide
實踐過程:
[root@oldboy ~]# touch /ett #==>建立測試文件/ett
[root@oldboy ~]# stat /ett #==>經過stat命令能夠看到文件的數字權限
File: `/ett'
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: 803h/2051d Inode: 98211 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2012-02-20 08:04:24.000000000 +0800
Modify: 2012-02-20 08:04:24.000000000 +0800
Change: 2012-02-20 08:04:24.000000000 +0800
那麼咱們如何得到這一文件的數字權限呢?
法一過程:(stat、sed、cut)
[root@oldboy ~]# stat /ett|sed -n '4p'#==>首先經過管道把stat結果傳給sed處理取出須要的行。
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
[root@oldboy ~]# stat /ett|sed -n '4p'|cut -d "/" -f1 #==>對上面的結果以/線爲分割符,而後取第1個字段。這裏以斜線分割不是惟一的方法,你們注意下。
Access: (0644
[root@oldboy ~]# stat /ett|sed -n '4p'|cut -d "/" -f1|cut -d "(" -f2 #==>這就是法一答案
#==>對上面的結果以(號爲分割符,而後取第2個字段,就會得出咱們須要的結果。
0644
特別說明:
1)上題中的sed -n '4p'是取結果的第二行的意思,也能夠用笨辦法head -4|tail -1替代。例:
[root@oldboy ~]# stat /ett|head -4|tail -1|cut -d "/" -f1|cut -d "(" -f2 #==>法二答案
0644
2)上題中的cut -d "/" -f1|cut -d "(" -f2部分,也能夠用awk,sed等命令替代。如例:
[root@oldboy ~]# stat /ett|head -4|tail -1|awk -F "/" '{print $1}'|awk -F "(" '{print $2}'
0644 #==>法三答案,awk法若是你們有不懂的,也不用糾結,本文後面問題裏會細講。
提示::此題考察了你們對stat ,cut,awk,head,tail,sed等命令組合用法,有對這些命令還不熟悉的同窗,能夠分步分批總結下。
注意:敲字符時成對出現的’’,{}內容,最好連續敲完,以避免後續落下。
法二過程:(stat)
固然還有更簡單的方法:
[root@oldboy ~]# stat -c %a /ett
644
注意:如何想到法二的思考過程,比答題更重要。當命令結果包含咱們須要的內容的時候,咱們要想到是否有具體的參數可以一步達到咱們須要的結果。
特別說明:
有關stat -c的用法能夠經過stat --help和man stat,info stat,這是全部命令的三大幫助殺手鐗,必需要掌握了。
[root@oldboy ~]# stat --help
Usage: stat [OPTION] FILE... #==>這是語法格式
Display file or file system status.
...省略部分...
-f, --file-system display file system status instead of file status
-c --format=FORMAT use the specified FORMAT instead of the default;
output a newline after each use of FORMAT
...省略部分...
#==>這是可用的參數,如-c。
The valid format sequences for files (without --file-system):
#==>這裏是對於文件適用的格式,既-c後接的格式。
%a Access rights in octal #==>以8進制形式顯示,即爲本文的答案
%A Access rights in human readable form #==>拓展以人類可讀的形式顯示權限
%b Number of blocks allocated (see %B)
%B The size in bytes of each block reported by %b
%d Device number in decimal
%D Device number in hex
%f Raw mode in hex
%F File type
%g Group ID of owner
%G Group name of owner
%h Number of hard links
%i Inode number
%n File name
%N Quoted file name with dereference if symbolic link
%o I/O block size
%s Total size, in bytes
...省略部分...
本題的拓展部分:
[root@oldboy ~]# ls -li /ett
98211 -rw-r--r-- 1 root root 0 Feb 20 08:04 /ett
[root@oldboy ~]# stat -c %a /ett
644
[root@oldboy ~]# stat -c %A /ett #==>獲取字符權限
-rw-r--r--
[root@oldboy ~]# stat -c %B /ett
512
[root@oldboy ~]# stat -c %b /ett
0
[root@oldboy ~]# stat -c %i /ett #==>inode信息
98211
[root@oldboy ~]# stat -c %n /ett
/ett
[root@oldboy ~]# stat -c %o /ett #==>block size
4096