Linux shell 的 test 命令用法詳解

原文鏈接:http://blog.csdn.net/duguteng/article/details/7725845

基本格式:
test expression

expression爲test命令構造的表達式。
這裏expression是test命令可以理解的任何有效表達式,該簡化格式將是讀者可能會踫見的最常用格式
返回值:
test命令或者返回0(真) 或者返回1(假).

test可理解的表達式類型分爲四類:

  •     表達式判斷
  •     字符串比較
  •     數字比較
  •     文件比較

1)判斷表達式

if test  (表達式爲真)
if test !表達式爲假
test 表達式1 –a 表達式 2                兩個表達式都爲真
test 表達式1 –o 表達式2                 兩個表達式有一個爲真

 

2)判斷字符串

test –n 字符串                          字符串的長度非零
test –z 字符串                           字符串的長度爲零
test 字符串1=字符串 2          字符串相等
test 字符串1 !=字符串2         字符串不等

 

3)判斷整數

test 整數1 –eq 整數2                       整數相等
test 整數 1 –ge 整數2                      整數1大於等於整數2
test 整數1 –gt 整數 2                       整數1大於整數2
test 整數1 –le 整數 2                       整數1小於等於整數2
test 整數1 –lt 整數 2                         整數1小於整數2
test 整數1 –ne 整數 2                      整數1不等於整數2

 
4)判斷文件

test  File1 –ef  File2                            兩個文件具有同樣的設備號和i結點號
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位
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            文件存在並且可執行

test xxx 可以簡寫成 [  xxx  ] 的形式。

注意:在使用"["簡寫test時,左中括號後面的空格和右括號前面的空格是必需的,如果沒有空格,Shell不可能辨別表達式何時開始何時結束.

也就是說

    test option file

可以全部改寫成:

    [ option file ]

例如:

 test –w File
 
改寫成    

[ –w File ]    

【示例】

//判斷第一個參數是否爲空字符串,不空則打印
if test -n "$1"
then
echo "$1"
fi

測試,放到文件當中
#!/bin/sh

if test -n "$1"
then
echo "$1"
fi

執行
chmod +x test.sh
./test.sh www.linuxpig.com

發佈了30 篇原創文章 · 獲贊 39 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章