shell中的test命令

1.test命令的基本知识

test是shell中的内置命令,用来检测某个条件是否成立,test命令通常和if语句一起使用
test命令通常可以在数值、字符串、文本这三个方面进行检测
test命令可以简写为[],用法[ expression ]

2.数值比较(可以是数值和变量)

比较 描述
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
#!/bin/bash
val=10
if[ $val1 -eq 10 ]
then
	echo 'equal'
fi

运行结果:equal

#!/bin/bash
val=`echo "scale=4;10\3 | bc"`
if[ $val1 -qt 2 ]
then
	echo 'yes'
fi

运行结果:报错 在test命令中不能使用浮点数

3.字符串比较

比较 描述
str1 = str2 检查str1是否和str2相同
str1 != str2 检查str1是否和str2不同
str1 > str2 检查str1是否比str2大
str1 < str2 检查str1是否比str2小
-n str1 检查str1的长度是否非0
-z str1 检查str1的长度是否为0
#!/bin/bash
testing=root
if [ $USER=$testing ]
then
	echo "welcome $tesing"
fi

运行结果:welcome root

val1=baseball
val2=hockey
if [ $val1 > $val2 ]
then
	echo "yes"
else
	echo "no"

运行结果:会出现hockey文件
原因为:大小写符号必须转义,否则shell会把他们当做重定向符号

val1=baseball
val2=hockey
if [ $val1 \> $val2 ]
then
	echo "yes"
else
	echo "no"

运行结果:no
这是由于按照ASCI码进行比较,c大于b

#!/bin/bash
val1='testing'
val2=' '
if [ -n "$val1" ]
then 
	echo "not empty"
else
	echo "empty"
fi

运行结果:not empty

#!/bin/bash
val1='testing'
val2=' '
if [ -z "$val2" ]
then 
	echo " empty"
else
	echo " not empty"
fi

运行结果:empty

4.文件比较

比较 描述
-d file 检查file是否存在并且为一个目录
-e file 检查file是否存在
-f file 检查file是否是存在并且为一个文件
-r file 检查file是否是存在并且可读
-s file 检查file是否是存在并且非空
-w file 检查file是否是存在并且可写
-x file 检查file是否是存在并且为可执行
-O file 检查file是否是存在并且属当前用户所有
-G file 检查file是否是存在并且默认组与当前用户相同
file1 -nt file2 file1是否比file2新
file1 -nt file2 file1是否比file2旧
#!/bin/bash
if [ -d $HOME ]
then
	echo "exist"
	cd $HOME
	ls -a 
else
	echo "no exist"

运行结果:exist,且查看该目录下的所有文件

#!/bin/bash
if [ -e $HOME ]
then
	echo "exist"
	if [ -e $HOME/tesing ]
		then 
			echo "appending date to this file "
			date >> $HOME/tesing
		else
			echo "creating this file"
			date > $HOME/testing
	else哦
		echo "sorry"

运行结果:appending date to this file(该文件之前建立过)

file=test
touch $file
if [ -s $file ]  ##判断存在且非空
then
	echo"exist and not empty"
else
	echo "exist and empty"
fi

运行结果:exist and empty

file=test
touch $file
if [ -G $file ]  ##
then
	echo "same group"
else
	echo "different group"
fi

运行结果:same group

if [ 01.sh -nt 02.sh ]  ##
then
	echo "01.sh比02.sh新"
else
	echo "01.sh比02.sh旧"
fi

运行结果:echo "01.sh比02.sh旧

if [ 01.sh -ot 02.sh ]  ##
then
	echo "01.sh比02.sh旧"
else
	echo "01.sh比02.sh新"
fi

运行结果:echo "01.sh比02.sh旧

5.复合条件测试(&&和||)

#!/bin/bash
if [ -d $HOME ] &&[ -w $HOME/testing ]
then
 	echo "exist and can write"```
 fi

运行结果: exist and can write

总结:
在这里插入图片描述

发布了111 篇原创文章 · 获赞 0 · 访问量 2549

猜你喜欢

转载自blog.csdn.net/qq_42024433/article/details/104311281