linux之Shell编程3:read键盘录入、shell的运算、测试命令test、if条件

目录

一、read键盘读入

二、shell的运算

三、测试命令

四、if语句


一、read键盘读入

命令:read从键盘读入数据,赋给变量。类似java中的Scanner.

eg:从键盘输入3个变量

#!/bin/sh
read f s t  #fst单词随便定义自己可以定义,自定定义的3个变量。外部脚本执行的时候,需要给我传递3个变量
echo "the first is $f"  #$为占位符号
echo "the seconda is $s"
echo "the third is $t"

运行脚本结果显示如下:

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ sh demo5.sh
10 20 30
the first is 10
the seconda is 20
the third is 30

注意:执行的时候可以有-x表示跟踪的意思。+后面是shell脚本里面写的命令,当shell脚本写的有问题的时候,可以用这个方式调试一下程序。

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ sh -x demo5.sh
+ read f s t
30 50 70
+ echo the first is 30
the first is 30
+ echo the seconda is 50
the seconda is 50
+ echo the third is 70
the third is 70

 二、shell的运算

shell只能计算整数,不能计算小数。expr命令,对整数进行运算。

linux之Shell编程3:read键盘录入、shell的运算、测试命令test、if条件_第1张图片

eg:注意空格的演示 ,注意乘号*要加上转义字符,因为*在linux中表示一个特殊的符号。

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr 10+5
10+5
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr10+5
expr10+5: command not found
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr 10 +5
expr: syntax error
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr 10 + 5
15
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr 10 - 5
5
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr 10 / 5
2
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr 10 \* 5
50
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr 10 - 2 \* 5  #这里先算的乘法,后算的减法
0
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr `expr 10 - 2` \* 5 
40    #这里先算的减法,后算的乘#法,相当于括号,先算里面的这个命令,然后把这个命令当成一个结果,再算外面的命令。

也可以变量进行操作:

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ num=30
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ echo `expr $num + 8`
38

不能对小数进行计算,咱们可以计算一下:没有小数点

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ expr 10 / 3
3

三、测试命令

这些命令都是在shell脚本里面执行的,配合if和else控制语句。因为怎么输出也不能显示一个true或者false

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ str1=10
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ str2=10
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ test str1=str2
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ test str1!=str2
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ echo "test str1=str2"
test str1=str2
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ echo "test $str1=$str2"
test 10=10
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ echo `test str1=st2`

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ echo `test strls!=st2`

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ 

linux之Shell编程3:read键盘录入、shell的运算、测试命令test、if条件_第2张图片

四、if语句

eg:我自己也认为test没有什么作用的,可以用[]进行简化。 

#!/bin/sh
# if test $1 then ... else ... fi   #其中$1占位符号,第一个参数
if [ -d $1 ]	                    #相当于test了
then
		echo "this is a directory!"
else
		echo "this is not a directory"
fi                                  #if 反过来写。

注意点:语句尤其注意空格 if [ -d $1 ],其它也是也是一样,不然会导致运行错误。

eg:我写找一个目录

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ pwd
/home/love/shelldir

运行脚本结果显示如下:

love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ sh demo6.sh /home/love/shelldir
this is a directory!
love@iZuf69ps3de0b3n4a50j7nZ:~/shelldir$ sh demo6.sh /home/love/shelldir/demo1.sh
this is not a directory

 

你可能感兴趣的:(Linux,Ubuntu,Linux)