shell学习之条件测试(参考shell脚本编程诀窍)
1关于test测试,查看man文档知表达式的判断
( EXPRESSION ) #EXPRESSION is true
! EXPRESSION #EXPRESSION is false
EXPRESSION1 -a EXPRESSION2 #both are true,-o means or
字符串是否为空,相等
-n STRING#the length of STRING is nonzero,-n can be removed
-z STRING#the length of STRING is zero(nonexists,or null)
#when comes to string, we use =
STRING1 = STRING2 #the strings are equal
STRING1 != STRING2 #the strings are not equal
数字的比较
#when comes to number,we use different eq ne and so on
INTEGER1 -eq INTEGER2 #INTEGER1 is equal to INTEGER2
-gegreater or equal
-gtgreater than
-le -lt -ne I
比较文件是否为链接文件
FILE1 -ef FILE2 #FILE1 and FILE2 have the same device and inode numbers
eg
# testtxt-ef txthardlink
# echo $?
0
# testtxt-ef txtlink(soft)
# echo $?
0
所以这个是测试是否是文件链接(包括软硬),大家可以自己试试
比较文件的修改时间
FILE1 -nt FILE2#FILE1 is newer/older (modification date) than FILE2,timestamp
FILE1 -ot FILE2 文件有修改时间modify time (强调内容改变) 改变时间change time(本质即相关属性改变)接触时间access time(被访问)
文件类型
-b FILE #type:block special
-c FILE #type:character special
-d FILE # a directory
-e FILE #FILE exists是否存在
-s FILE #FILE exists and has a> -f FILE #a regular file
-u FILE #set user-ID SUID
-g FILE #FILE exists and is set-group-ID使用时暂时拥有文件所属组的权限SGID
-G FILE #FILE exists and is owned by the effective group> -h FILE #a symbolic link (same as -L)
-k FILE #FILE exists and has its sticky bit set sticky位其他用户只能添加不能删除
-L FILE #FILE exists and is a symbolic link (same as -h)
-O FILE #FILE exists and is owned by the effective user> -p FILE #a named pipe
-S FILE #FILE exists and is a socket
-r FILE #FILE exists and read permission is granted
you canuse -w,write,-xexecute
-t FD #file descriptor FD is opened on a terminal
很多,但有规律,常用的并不多
2 上面的测试还可用于类似[ -e $num ]结构中
3 if/then条件测试结构(还有case,while,等结构可能后面会涉及,不懂请自行baidu)
①if[ condition ]
then
COMMAND
fi
or
if[ condition ];then
COMMAND
fi
②if[ condition ];then
COMMAND1
else
COMMAND2
fi
③if[ condition ];then
COMMAND1
elif[ condition ];then
COMMAND2
else
COMMAND3
fi
big eg.
#if1.sh
#!/bin/bash
#
read -p "guss who am i?"HELLO
test -z $HELLO&&echo "wrong argv please reinput!"&&exit 1
if [ "$HELLO" = "Jack" ];then
echo "oh,you are jack!"
elif [ "$HELLO" = "Kitty" ];then
echo "oh,you are Kitty!"
elif [ "$HELLO" = "Mike" ];then
echo "oh,you are Mike!"
else
echo "sorry i don't remember."
echo "ok,my name is $HELLO"
fi
通常if then可以改为` conditon `&&条件ok||条件不ok
3 ` `与[]的区别
通常表现在以下几个方面
[ ]使用-a,-o连接多个逻辑表达式,而` `使用&&,||连接多个表达式
[ ]:通配符不起作用,` `会展开通配符
[ ]不能使用比较运算符,如>,
页:
[1]