【Linux】一步一步学Linux——test命令(252)
生活随笔
收集整理的這篇文章主要介紹了
【Linux】一步一步学Linux——test命令(252)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
00. 目錄
文章目錄
- 00. 目錄
- 01. 命令概述
- 02. 命令格式
- 03. 常用選項
- 04. 參考示例
- 05. 附錄
01. 命令概述
test 命令用于檢查某個條件是否成立,它可以進行數值、字符和文件三個方面的測試。
02. 命令格式
用法:test EXPRESSIONtest03. 常用選項
#1. 關于兩個整數之間的判定,例如 test n1 -eq n2 -eq 兩數值相等 (equal) -ne 兩數值不等 (not equal) -gt n1 大于 n2 (greater than) -lt n1 小于 n2 (less than) -ge n1 大于等于 n2 (greater than or equal) -le n1 小于等于 n2 (less than or equal) #2. 判定字符串 test -z string 判定字符串是否為 0 ?若 string 為空字符串,則為 true test -n string 判定字符串是否非為 0 ?若 string 為空字符串,則為 false。 注: -n 亦可省略 test str1 = str2 判定 str1 是否等于 str2 ,若相等,則回傳 true test str1 != str2 判定 str1 是否不等于 str2 ,若相等,則回傳 false #3. 多重條件判定,例如: test -r filename -a -x filename -a (and)兩狀況同時成立例如 test -r file -a -x file,則 file 同時具有 r 與 x 權限時,才返回 true。 -o (or)兩狀況任何一個成立例如 test -r file -o -x file,則 file 具有 r 或 x 權限時,就可返回 true。 ! 邏輯非如 test ! -x file ,當 file 不具有 x 時,返回 true#4. 文件相關判斷 test File1 –ef File2 兩個文件是否為同一個文件,可用于硬連接。主要判斷兩個文件是否指向同一個inode。 test File1 –nt File2 判斷文件1是否比文件2新 test File1 –ot File2 判斷文件1比是否文件2舊 test –b file #文件是否塊設備文件 test –c File #文件并且是字符設備文件 test –d File #文件并且是目錄 test –e File #文件是否存在 (常用) test –f File #文件是否為正規文件 (常用) test –g File #文件是否是設置了組id test –G File #文件屬于的有效組ID test –h File #文件是否是一個符號鏈接(同-L) test –k File #文件是否設置了Sticky bit位 test –b File #文件存在并且是塊設備文件 test –L File #文件是否是一個符號鏈接(同-h) test –o File #文件的屬于有效用戶ID test –p File #文件是一個命名管道 test –r File #文件是否可讀 test –s File #文件是否是非空白文件 test –t FD #文件描述符是在一個終端打開的 test –u File #文件存在并且設置了它的set-user-id位 test –w File #文件是否存在并可寫 test –x File #文件屬否存在并可執行04. 參考示例
4.1 判斷文件是否存在
[deng@localhost ~]$ test test.txt [deng@localhost ~]$ echo $? 0 [deng@localhost ~]$存在返回0,不存返回1
4.2 斷目錄是不是存在
[deng@localhost ~]$ test -d /home [deng@localhost ~]$ echo $? 0 [deng@localhost ~]$4.3 判斷文件是否有寫的權限
[deng@localhost ~]$ test -w test.cpp [deng@localhost ~]$ echo $? 0 [deng@localhost ~]$4.4 判斷文件是否為空文件
[deng@localhost ~]$ test -s test.cpp [deng@localhost ~]$ echo $? 0 [deng@localhost ~]$4.5 判斷test.c是不是比test.cpp新
[deng@localhost ~]$ test test.c -nt test.cpp [deng@localhost ~]$ echo $? 0 [deng@localhost ~]$4.6 判斷2是不是等于3
[deng@localhost ~]$ test 2 -eq 3 [deng@localhost ~]$ echo $? 1 [deng@localhost ~]$4.7 判斷3是不是大于2
[deng@localhost ~]$ test 3 -gt 2 [deng@localhost ~]$ echo $? 0 [deng@localhost ~]$4.8 判斷A是不是等于B
[deng@localhost ~]$ A="aaa" [deng@localhost ~]$ B="bbb" [deng@localhost ~]$ test A = B [deng@localhost ~]$ echo $? 1 [deng@localhost ~]$4.9 判斷A是不是不等于B
[deng@localhost ~]$ A="aaa" [deng@localhost ~]$ B="bbb" [deng@localhost ~]$ test A != B [deng@localhost ~]$ echo $? 0 [deng@localhost ~]$4.10 當home為目錄,并且可寫時為真
[deng@localhost ~]$ test -d /home -a -w /home [deng@localhost ~]$ echo $? 1 [deng@localhost ~]$05. 附錄
參考:【Linux】一步一步學Linux系列教程匯總
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的【Linux】一步一步学Linux——test命令(252)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Linux】一步一步学Linux——l
- 下一篇: 【Linux】一步一步学Linux——o