Shell系列(二)——read,expr,test测试语句,if测试语句

一、read,expr语句

read语句:从键盘读入数据,赋给变量。

image.png

与命令行的交互

# read.sh
#!/bin/bash
read first second third
echo "1 para $first"
echo "2 para $second"
echo "3 para $third"
Shell系列(二)——read,expr,test测试语句,if测试语句_第1张图片
image.png

expr命令:作Shell变量的算术运算。所有操作数(运算符)之间必须有空格。如"3 + 5"。


二、test测试语句

格式:test 测试条件
测试范围:整数,字符串,文件
字符串和变量

# 是否相等
test str1==str2  
# 是否不相等
test str1!=str2  
# 测试是字符串是否不空
test str1  
# 测试字符串是否为空
test -n(或-z) str1

整数比较:

# 测试整数相等(==)
test int1 -eq int2
# >=
test int1 -ge int2
# >
test int1 -gt int2
# <=
test int1 -le int2
# <
test int1 -lt int2
# !=
test int1 -ne int2

文件测试:

# 是否为目录:
test -d file
# 是否为文件:
test -f file
# 是否执行/读/写:
test -x/-r/-w file
# 是否存在:
test -e file
# 是否为空文件:
test -s file

单独用test意义不大,需要和流程控制语句配合。同时test也可以简写如[ -x file ],需注意这么写两边都要加空格。


三、if语句

语法:if 条件 then 语句 fi
需要注意,结尾是要以fi结尾的,这与其他语言中的if语句不一样。
测试代码

#!/bin/bash
echo "if test"
if [ -x /bin/ls ];then
/bin/ls
fi

输出

image.png

if/else
语法

if condition1 
    then condition2 
elif condition 3
else condition 4 
fi

多个条件的联合
-a 或 &&:逻辑与。
-o 或 ||:逻辑或。

你可能感兴趣的:(Shell系列(二)——read,expr,test测试语句,if测试语句)