學(xué)習(xí)啦>學(xué)習(xí)電腦>操作系統(tǒng)>Linux教程>

linux test命令詳解

時(shí)間: 佳洲1085 分享

  test命令是linux下的一個(gè)命令,那么它的具體語(yǔ)法是怎樣的呢?下面由學(xué)習(xí)啦小編為大家整理了linux test命令的相關(guān)知識(shí),希望對(duì)大家有幫助!

  1.linux test命令基本格式

  test expression

  expression為test命令構(gòu)造的表達(dá)式。

  這里expression是test命令可以理解的任何有效表達(dá)式,該簡(jiǎn)化格式將是讀者可能會(huì)踫見的最常用格式

  2.linux test命令返回值:

  test命令或者返回0(真) 或者返回1(假).

  3.linux test命令可理解的表達(dá)式類型分為四類:

  表達(dá)式判斷

  字符串比較

  數(shù)字比較

  文件比較

  1)判斷表達(dá)式

  if test (表達(dá)式為真)

  if test !表達(dá)式為假

  test 表達(dá)式1 –a 表達(dá)式 2 兩個(gè)表達(dá)式都為真

  test 表達(dá)式1 –o 表達(dá)式2 兩個(gè)表達(dá)式有一個(gè)為真

  2)判斷字符串

  test –n 字符串 字符串的長(zhǎng)度非零

  test –z 字符串 字符串的長(zhǎng)度為零

  test 字符串1=字符串 2 字符串相等

  test 字符串1 !=字符串2 字符串不等

  3)判斷整數(shù)

  test 整數(shù)1 –eq 整數(shù)2 整數(shù)相等

  test 整數(shù) 1 –ge 整數(shù)2 整數(shù)1大于等于整數(shù)2

  test 整數(shù)1 –gt 整數(shù) 2 整數(shù)1大于整數(shù)2

  test 整數(shù)1 –le 整數(shù) 2 整數(shù)1小于等于整數(shù)2

  test 整數(shù)1 –lt 整數(shù) 2 整數(shù)1小于整數(shù)2

  test 整數(shù)1 –ne 整數(shù) 2 整數(shù)1不等于整數(shù)2

  4)判斷文件

  test File1 –ef File2 兩個(gè)文件具有同樣的設(shè)備號(hào)和i結(jié)點(diǎn)號(hào)

  test File1 –nt File2 文件1比文件2 新

  test File1 –ot File2 文件1比文件2 舊

  test –b File 文件存在并且是塊設(shè)備文件

  test –c File 文件存在并且是字符設(shè)備文件

  test –d File 文件存在并且是目錄

  test –e File 文件存在

  test –f File 文件存在并且是正規(guī)文件

  test –g File 文件存在并且是設(shè)置了組ID

  test –G File 文件存在并且屬于有效組ID

  test –h File 文件存在并且是一個(gè)符號(hào)鏈接(同-L)

  test –k File 文件存在并且設(shè)置了sticky位

  test –b File 文件存在并且是塊設(shè)備文件

  test –L File 文件存在并且是一個(gè)符號(hào)鏈接(同-h)

  test –o File 文件存在并且屬于有效用戶ID

  test –p File 文件存在并且是一個(gè)命名管道

  test –r File 文件存在并且可讀

  test –s File 文件存在并且是一個(gè)套接字

  test –t FD 文件描述符是在一個(gè)終端打開的

  test –u File 文件存在并且設(shè)置了它的set-user-id位

  test –w File 文件存在并且可寫

  test –x File 文件存在并且可執(zhí)行

  test xxx 可以簡(jiǎn)寫成 [ xxx ] 的形式。

  注意:在使用"["簡(jiǎn)寫test時(shí),左中括號(hào)后面的空格和右括號(hào)前面的空格是必需的,如果沒有空格,Shell不可能辨別表達(dá)式何時(shí)開始何時(shí)結(jié)束.

  也就是說

  test option file

  可以全部改寫成:

  [ option file ]

  例如:

  test –w File

  改寫成

  [ –w File ]

  5.linux test命令示例

  //判斷第一個(gè)參數(shù)是否為空字符串,不空則打印

  if test -n " class="main">

linux test命令詳解

時(shí)間: 佳洲1085 分享

  then

  echo " class="main">

linux test命令詳解

時(shí)間: 佳洲1085 分享

  fi

  測(cè)試,放到文件當(dāng)中

  #!/bin/sh

  if test -n " class="main">

linux test命令詳解

時(shí)間: 佳洲1085 分享

  then

  echo " class="main">

3583082