shell中的运算及应用示例

1.运算方式及运算符号

运算符号 意义
+,- 加法,减法
*,/,% 乘法,除法,取余
** 幂运算
++,-- 自增加,自减少
<,<=,>,>= 比较符号
=,+=,-=,*=,/=,%= 赋值运算,例如a+=1相当于a=a+1

2.SHELL中常用的运算命令

运算操作与运算命令 含义
(()) 用于整数运算
let 用于整数运算,与(())类似
expr 用于整数运算,功能相对较多
bc linux下的运算器,时和整数及小数运算
$[ ] 用户整数运算

示例:

练习:

编写一个10秒倒计时的脚本

#!/bin/bash
for ((Time_Num=10;Time_Num>=0;Time_Num--))
do
echo -n  "$Time_Num "
echo -ne "\r\r"
sleep 1
done

编写一个一分10秒的脚本

#!/bin/bash
read -p "Please input minute follow the script: "  M
read -p "Please input second follow the script: "  S
I=$[M*60+S]
for ((P=$I;P>=0;P--))
do
    A=$[$P/60]
    B=$[$P%60]
    echo -ne "\r$A:$B \r"
    sleep 1
done

利用以上命令制作一个计算器要求如下
执行 Calculator.sh 后显示
请输入您要操作的数字:
请输入要操作的运算:
请输入要操作的第二个数字 :

>> 执行后显示操作后的数值 <<

#!/bin/bash
read -p "please input first number: " a
read -p "please input calculator tactique: " b
read -p "please input second number: " c
echo $[$a$b$c]

练习:服务自动部署示例
脚本要求:
执行脚本 lamp.sh
脚本执行后部署好论坛,并设定 apache 的网络接口为 8080

#!/bin/bash
Auto_Discuz()
{
/usr/bin/expect << EOF
set timeout 30
spawn ssh root@$1
expect {
    "yes/no" { send "yes\r";exp_continue }
    "password:" { send "westos\r" }
}
expect "]#" { send "yum install httpd -y\r" }
expect "]#" { send "yum install mariadb-server -y\r"}
expect "]#" { send "yum install php-mysql.x86_64 -y\r"}
expect "]#" { send "systemctl start httpd\r" }
expect "]#" { send "systemctl start mariadb\r" }
expect eof
EOF
}
Auto_Connect()
{
/usr/bin/expect << EOF
set timeout 30
spawn ssh root@$1
expect {
    "yes/no" { send "yes\r";exp_continue }
    "password:" { send "westos\r" }
}
expect "]#" { send "cd /var/www/html/\r" }
expect "]#" { send "unzip /var/www/html/Discuz_X3.2_SC_UTF8.zip >> /dev/null \r" }
expect "]#" { send "chmod 777 /var/www/html/upload/ -R\r" }
expect "]#" { send "systemctl restart httpd\r" }
expect eof
EOF
}
Auto_Httpd()
{
/usr/bin/expect << EOF
set timeout 30
spawn ssh root@$1
expect {
    "yes/no" { send "yes\r";exp_continue }
    "password:" { send "westos\r" }
}
expect "]#" { send "sed "/^Listen/cListen 8080" -i /etc/httpd/conf/httpd.conf\r" }
expect "]#" { send "yum restart httpd -y\r" }
expect eof
EOF
}
yum install expect -y
Auto_Discuz $1
scp /home/kiosk/Downloads/Discuz_X3.2_SC_UTF8.zip root@$1:/var/www/html
Auto_Connect $1
firefox -new-tab $1/upload/install
Auto_Httpd $1


猜你喜欢

转载自blog.csdn.net/qq_40303205/article/details/80834988
今日推荐