shell(二)

本文介绍了Shell中的read和expr命令的基本用法,并展示了如何通过这些命令进行简单的输入读取及算术运算。此外,还详细解释了使用test命令进行字符串、整数及文件属性测试的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

read 命令

[root@iZtoz99sjuwqcnZ test]# read a b c
1 2 3
[root@iZtoz99sjuwqcnZ test]# a
-bash: a: command not found
[root@iZtoz99sjuwqcnZ test]# $a
-bash: 1: command not found
[root@iZtoz99sjuwqcnZ test]# echo $a
1

expr命令

Shell 变量的运算符
expr 3 + 5

[root@iZtoz99sjuwqcnZ ~]# var1=8
[root@iZtoz99sjuwqcnZ ~]# var2=2
[root@iZtoz99sjuwqcnZ ~]# expr $var1 - 5
3
[root@iZtoz99sjuwqcnZ ~]# expr $var1 / $var2
4
[root@iZtoz99sjuwqcnZ ~]# expr $var1 \* $var2
16
[root@iZtoz99sjuwqcnZ test]# cat expr.sh 
#!/bin/bash
a=10
b=20
c=30
value1=`expr $a + $b + $c`
echo "The value of value1 is $value1"
value2=`expr $c / $b`
echo "The value of value2 is $value2"
value3=`expr $b \* $c`
echo "The value of value3 is $value3"
value4=`expr $a + $c / $c`
echo "The value of value4 is $value4"
[root@iZtoz99sjuwqcnZ test]# ./expr.sh 
The value of value1 is 60
The value of value2 is 1
The value of value3 is 600
The value of value4 is 11

变量测试语句

test
格式:
test 测试条件
测试范围:整数、字符串、文件

字符串和变量:
test str1 =- str2 //是否相等
test str1 != str2 //是否不想等
test str1 // 检测字符串是否不空

test -n str1 测试字符串是否为空
或
test -z str1 检测字符串是否为空
测试整数
test int1 -eq int2
test int1 -gt int2
test int1 -ge int2
test int1 -lt int2
test int1 -le int2
test int1 -ne int2

说明:也可以缩写成为:[int1 -lt int2]

文件测试
test -d file //文件是否为目录
test -f file
test -x file
test -r file
test -w file
test -e file //是否存在
test -s file //文件是否为空

说明:也可以写成:[-s file]

多条件的联合

-a or && :逻辑与
-o or || :逻辑或

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值