shell-数值运算符与read交互式赋值
1.常用运算符
expr :数值运算
expr 变量1 运算符 变量2
/
%
运算符与变量之间必须又一个空格
[root@bigdata111 shell]# A=10
[root@bigdata111 shell]# B=20
[root@bigdata111 shell]# expr $A+$B
10+20
[root@bigdata111 shell]# expr $A + $B
30
[root@bigdata111 shell]# expr $A - $B
-10
[root@bigdata111 shell]# expr $A \* $B
200
[root@bigdata111 shell]# expr $A / $B
0
[root@bigdata111 shell]# expr $A % $B
10
[root@bigdata111 shell]#
2.结果赋值给变量
[root@bigdata111 shell]# abc=$(expr $A + $B)
[root@bigdata111 shell]# echo $abc
30
[root@bigdata111 shell]#
3.符号作用
3.1双引号
双引号 " " 当值存在空格或者特殊字符
[root@bigdata111 shell]# webserver=nginx 1.11
bash: 1.11: command not found...
[root@bigdata111 shell]# echo $webserver
[root@bigdata111 shell]# webserver="nginx 1.11"
[root@bigdata111 shell]# echo $webserver
nginx 1.11
[root@bigdata111 shell]# echo $Linux
[root@bigdata111 shell]# Linux=7.2
[root@bigdata111 shell]# system=" CentOS $Linux"
[root@bigdata111 shell]# echo $system
CentOS 7.2
[root@bigdata111 shell]#
3.2单引号
’ ’
[root@bigdata111 shell]# kernel="3.10 $Linux"
[root@bigdata111 shell]# echo $kernel
3.10 7.2
[root@bigdata111 shell]# kernel='3.10 $Linux'
[root@bigdata111 shell]# echo $kernel
3.10 $Linux
[root@bigdata111 shell]#
3.3反撇号
``
主要用于命令替换,允许讲某个命令的屏幕输出结果赋值给变量
3.交互式赋值
read命令用来提示用户输入信息,从而实现简单的交互式过程
[root@bigdata111 shell]# read kernel
12
[root@bigdata111 shell]# echo $kernel
12
[root@bigdata111 shell]# read a b c
1 2 3
[root@bigdata111 shell]# echo $a $b $c
1 2 3
[root@bigdata111 shell]# read -p "Please enter your name!" nem
bash: !": event not found
[root@bigdata111 shell]# read -p "Please enter your password:" password
Please enter your password:123
[root@bigdata111 shell]# echo $password
123
[root@bigdata111 shell]#
实例1:身份验证
判断用户名是root,密码是123456就能成功登陆;否则提示账号或密码错误
[root@bigdata111 shell]# vi user.sh
#! /bin/bash
#This is a script
#user=root
read -p "Please enter your UserName : " name
echo "Your UserName is : $name"
if [ $name == root ]
then
read -p "Please enter your Password : " password
if [ $password == 123456 ]
then
echo "Good! Success"
else
echo "Username or Password error"
fi
fi
执行:
[root@bigdata111 shell]# sh user.sh
Please enter your UserName : root
Your UserName is : root
Please enter your Password : 123456
Good! Success
[root@bigdata111 shell]#