前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >test 命令

test 命令

作者头像
用户1679793
发布2020-11-02 14:35:24
5900
发布2020-11-02 14:35:24
举报

Shell test 命令

每一种合理完整的编程语言都可以测试一个条件,然后根据测试的结果进行操作。Bash有test命令、各种括号和圆括号操作符以及if/then构造。

与test命令相关的命令和符号:

  • If/then条件判断。
  • 内置的[]中括号和[[]双中括号,[[]]比[]更灵活和强大,可以说是增强版。
  • (())和let,一般用于算术表达式和计算比较。
代码语言:javascript
复制
[root@localhost shell]# type test
test is a shell builtin
[root@localhost shell]# type [
[ is a shell builtin
[root@localhost shell]# type [[
[[ is a shell keyword
[root@localhost shell]# type let
let is a shell builtin

If/then可以测试任何命令,而不仅仅是括号内的条件

代码语言:javascript
复制
#!/bin/bash
if cmp a.txt b.txt &> /dev/null
then
    echo 'Files a and b are identical.'
else
    echo 'Files a and b are diff.'
fi

if/then测试条件格式一:

代码语言:javascript
复制
if [ condition-true ]
then
   command 1
   command 2
   ...
else  # Or elif ...
      # Adds default code block executing if original condition tests false.
   command 3
   command 4
   ...
Fi

if/then测试条件格式二:

代码语言:javascript
复制
if [ condition1 ]
then
   command1
   command2
   command3
elif [ condition2 ]
# Same as else if
then
   command4
   command5
else
   default-command
fi
 

 

使用(())进行算术测试

代码语言:javascript
复制
#!/bin/bash
var1=7
var2=10

if (( var1 > var2 )) # not $var1 $var2, but is ok.
then
    echo "var1 is greater than var2"
else
    echo "var1 is less than var2"
fi
exit 0

数值比较

比较

描述

n1 -eq n2

检查n1是否与n2相等

n1 -ge n2

检查n1是否大于或等于n2

n1 -gt n2

检查n1是否等于n2

n1 -le n2

检查n1是否小于或大于n2

n1 -lt n2

检查n1是否小于n2

n1 -ne n2

检查n1是否不等于n2

代码语言:javascript
复制
#!/bin/bash

num1=6
num2=9
if [ $num1 -ne $num2 ]
then
    echo "$num1 is not equal to $num2"
fi

字符串比较

参数

说明

Str1 = str2

检查str1是否和str2相同

Str1 != str2

检查str1是否和str2不同

-z str1

检查str1是否为零

-n str1

检查str1是否非零

Str1 > str2

检查str1是否大于syr2

Str1 < str2

检查str1是否小于str2

文件比较

比较

说明

-e file

检查file是否存在

-r file

检查file是否存在并可读

-w file

检查file是否存在并可写

-x file

检查file是否存在并可执行

-s file

检查file是否存在并非空

-d file

检查file是否存在并是一个目录

-f file

检查file是否存在并是一个文件

-c file

检查file是否字符型特殊文件

-b file

检查file是否块设备文件

代码语言:javascript
复制
#!/bin/bash

device1="/dev/sda1"
if [ -b "$device1" ]
then
    echo "$device1 is a block device."
fi

device2='/dev/tty0'
if [ -c "$device2" ]
then
    echo "$device2 is a character device."
fi
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-10-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档