linux shell 入门学习笔记14 shell脚本+数学计算

本文介绍了Shell脚本的基础知识,包括shebang、变量引用、数学计算以及条件判断。展示了如何开发计算脚本和Nginx服务状态检测脚本。还讨论了expr命令、bc计算器以及awk在数值计算中的应用。

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

概念

把复杂的命令执行过程,通过逻辑代码,组成一个脚本文件的方式就叫做shell脚本。

shebang

#! /bin/bash
#! /bin/perl
#! /bin/python

执行脚本的方式

source my_first.sh
. my_first.sh

bash my_first.sh
./my_first.sh

变量引用
${var} 取出变量结果
$() 在括号中执行命令,且拿到命令的执行结果
`` 在括号中执行命令,且拿到命令的执行结果
$var 取出变量结果
() 开启子shell执行命令

xiao123@xiao123:~/Downloads/shscripts$ echo "当前用户是:$(whoami)"
当前用户是:xiao123
xiao123@xiao123:~/Downloads/shscripts$ echo "当前用户是:`whoami`"
当前用户是:xiao123
xiao123@xiao123:~/Downloads/shscripts$ var=xiao123
xiao123@xiao123:~/Downloads/shscripts$ echo "当前用户是:${var}"
当前用户是:xiao123
xiao123@xiao123:~/Downloads/shscripts$ echo "当前用户是:$var"
当前用户是:xiao123
xiao123@xiao123:~/Downloads/shscripts$

数学计算

支持的运算符展示
数学计算1

Linux用于计算的命令展示
shell基础命令只支持整数,小数运算需要使用bc命令
运算命令

双小括号(())

用法
(())用法
演示:

xiao123@xiao123:~/Downloads/shscripts$ echo $((5<7))   #为True,1
1
xiao123@xiao123:~/Downloads/shscripts$ echo $((5>7))   #为Fase,0
0
xiao123@xiao123:~/Downloads/shscripts$

脚本开发

1.想好脚本的功能,作用,以及需求
2.转换为shell代码

开发一个,接收用户输入数字,且对运算符号判断,最终的出结果的一个计算脚本

  1. 接收用户输入
  2. 对用户输入的不是数字进行判断
  3. 对输入的运算符进行判断
  4. 最终进行结果计算,输出打印

代码

xiao123@xiao123:~/Downloads/shscripts$ cat ./calculation.sh
#! /bin/bash

do_usage() {
        printf "Please input an integer!!!\n"
        exit 1
}

read -p "Please input first number: " first

if [ -n "`echo ${first}|sed 's/[0-9]//g'`" ];
then
        do_usage
fi

read -p "Please input an operator: " operator

if [ ${operator} != '+' ] && [ ${operator} != '-' ] && [ ${operator} != '/' ] && [ ${operator} != '*' ];
then
        echo "Please input [+/-/*//]!!!"
        exit 2
fi

read -p "Please input second number: " second

if [ -n "`echo ${second}|sed 's/[0-9]//g'`" ];
then
        do_usage
fi

echo "${first}${operator}${second}=" $((${first}${operator}${second}))
xiao123@xiao123:~/Downloads/shscripts$

运行结果

xiao123@xiao123:~/Downloads/shscripts$ ./calculation.sh
Please input first number: qew123
Please input an integer!!!
xiao123@xiao123:~/Downloads/shscripts$ ./calculation.sh
Please input first number: 123
Please input an operator: eeee
Please input [+/-/*//]!!!
xiao123@xiao123:~/Downloads/shscripts$ ./calculation.sh
Please input first number: 123
Please input an operator: +
Please input second number: 12
123+12= 135
xiao123@xiao123:~/Downloads/shscripts$
let命令运算

let命令的执行,效果等同于双小括号(())
但是,双小括号(())效率更高

#对比
xiao123@xiao123:~/Downloads/shscripts$ num=5
xiao123@xiao123:~/Downloads/shscripts$ num=num+5
xiao123@xiao123:~/Downloads/shscripts$ echo ${num}
num+5
xiao123@xiao123:~/Downloads/shscripts$ num=5+5
xiao123@xiao123:~/Downloads/shscripts$ echo ${num}
5+5
xiao123@xiao123:~/Downloads/shscripts$
#let命令
xiao123@xiao123:~/Downloads/shscripts$ num=5
xiao123@xiao123:~/Downloads/shscripts$ let num=num+5
xiao123@xiao123:~/Downloads/shscripts$ echo ${num}
10
xiao123@xiao123:~/Downloads/shscripts$ let num=5+5
xiao123@xiao123:~/Downloads/shscripts$ echo ${num}
10
xiao123@xiao123:~/Downloads/shscripts$

脚本开发,对于nginx运行状态检测

#! /bin/bash

CheckUrl(){
	timeout=5
	fails=0
	success=0
	while true
		do
			wget --timeout=${timeout} --tries=1 http://www.baidu.com -q -o /dev/null
			if [ $? -ne 0 ];
				then
					let fails=fails+1
			else
					let success=success+1
			fi
			if [ ${success} -ge 1 ];
				then
					echo "恭喜你,服务运行正常"
					exit 0
			fi
			if [ ${fails} -ge 2 ];
				then
					echo "糟糕了,服务运行异常,请检查服务器状态"
					exit 2
			fi
		done
}

CheckUrl

# 运行结果
xiao123@xiao123:~/Downloads/shscripts$ ./let_test.sh
恭喜你,服务运行正常
xiao123@xiao123:~/Downloads/shscripts$
expr命令

简单的计算器执行命令。

xiao123@xiao123:~/Downloads/shscripts$ expr --help
Usage: expr EXPRESSION
  or:  expr OPTION

      --help     display this help and exit
      --version  output version information and exit

Print the value of EXPRESSION to standard output.  A blank line below
separates increasing precedence groups.  EXPRESSION may be:

  ARG1 | ARG2       ARG1 if it is neither null nor 0, otherwise ARG2

  ARG1 & ARG2       ARG1 if neither argument is null or 0, otherwise 0

  ARG1 < ARG2       ARG1 is less than ARG2
  ARG1 <= ARG2      ARG1 is less than or equal to ARG2
  ARG1 = ARG2       ARG1 is equal to ARG2
  ARG1 != ARG2      ARG1 is unequal to ARG2
  ARG1 >= ARG2      ARG1 is greater than or equal to ARG2
  ARG1 > ARG2       ARG1 is greater than ARG2

  ARG1 + ARG2       arithmetic sum of ARG1 and ARG2
  ARG1 - ARG2       arithmetic difference of ARG1 and ARG2

  ARG1 * ARG2       arithmetic product of ARG1 and ARG2
  ARG1 / ARG2       arithmetic quotient of ARG1 divided by ARG2
  ARG1 % ARG2       arithmetic remainder of ARG1 divided by ARG2

  STRING : REGEXP   anchored pattern match of REGEXP in STRING

  match STRING REGEXP        same as STRING : REGEXP
  substr STRING POS LENGTH   substring of STRING, POS counted from 1
  index STRING CHARS         index in STRING where any CHARS is found, or 0
  length STRING              length of STRING
  + TOKEN                    interpret TOKEN as a string, even if it is a
                               keyword like 'match' or an operator like '/'

  ( EXPRESSION )             value of EXPRESSION

Beware that many operators need to be escaped or quoted for shells.
Comparisons are arithmetic if both ARGs are numbers, else lexicographical.
Pattern matches return the string matched between \( and \) or null; if
\( and \) are not used, they return the number of characters matched or 0.

Exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null
or 0, 2 if EXPRESSION is syntactically invalid, and 3 if an error occurred.

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report any translation bugs to <https://translationproject.org/team/>
Full documentation <https://www.gnu.org/software/coreutils/expr>
or available locally via: info '(coreutils) expr invocation'
xiao123@xiao123:~/Downloads/shscripts$

实践
运算

expr 命令并不是很好用,基于空格传输参数,但是在shell中一些元字符都是有特殊含义的。
xiao123@xiao123:~/Downloads/shscripts$ expr 5 \+ 3
8
xiao123@xiao123:~/Downloads/shscripts$ expr 5 \- 3
2
xiao123@xiao123:~/Downloads/shscripts$ expr 5 \* 3
15
xiao123@xiao123:~/Downloads/shscripts$ expr 5 \/ 3
1
xiao123@xiao123:~/Downloads/shscripts$

求长度

xiao123@xiao123:~/Downloads/shscripts$ expr length 123456789
9
xiao123@xiao123:~/Downloads/shscripts$

逻辑运算

xiao123@xiao123:~/Downloads/shscripts$ expr 5 \> 6
0
xiao123@xiao123:~/Downloads/shscripts$ expr 5 \< 6
1
xiao123@xiao123:~/Downloads/shscripts$

模式匹配
2个特殊符号:

  • : 冒号,计算字符串字符的数量,Yuchao 6个字符
  • .* 任意字符重复0次或者多次

语法
expr 字符串 “:” “.*”

xiao123@xiao123:~/Downloads/shscripts$ expr yc.png ":" ".*"
6
xiao123@xiao123:~/Downloads/shscripts$ expr yc.png ":" ".*"  #统计文件中字符个数
6
xiao123@xiao123:~/Downloads/shscripts$ expr yc.png ":" ".*j"  #最后的模式可以自定义
0
xiao123@xiao123:~/Downloads/shscripts$ expr yc.png ":" "p.*"  #最后的模式可以自定义
0
xiao123@xiao123:~/Downloads/shscripts$ expr yc.png ":" "y.*"  #最后的模式可以自定义
6
xiao123@xiao123:~/Downloads/shscripts$ expr yc.png ":" ".*p"  #最后的模式可以自定义
4
xiao123@xiao123:~/Downloads/shscripts$

脚本开发
需求:执行脚本,传入一个文件名,然后判断该文件,是否是jpg图片文件

xiao123@xiao123:~/Downloads/shscripts$ ./expr_test.sh chaochao_1.jpg
这的确是chaochao_1.jpg结尾的文件
xiao123@xiao123:~/Downloads/shscripts$ cat ./expr_test.sh
#! /bin/bash

if expr "$1" ":" ".*\.jpg" >> /dev/null
        then
                echo "这的确是$1结尾的文件"
else
				echo "这不是jpg结尾的文件"
fi
xiao123@xiao123:~/Downloads/shscripts$

找出长度不大于为5的单词

xiao123@xiao123:~/Downloads/shscripts$ ./expr_test1.sh
I
am
Yu
I
you
to
xiao123@xiao123:~/Downloads/shscripts$ cat ./expr_test1.sh
#! /bin/bash

for str1 in I am Yu chao, I teach you to learn linux.
        do
                if [ `expr length ${str1}` -lt 5 ]
                        then
                                echo ${str1}
                fi
        done
xiao123@xiao123:~/Downloads/shscripts$
bc 命令

bc计算器
awk支持数值计算
中括号运算

bc当作计算器来用的,命令行的计算器。
例子1

xiao123@xiao123:~/Downloads/shscripts$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
2+2
4
4*4
16
1-1
0
1-2
-1
2.24/2
1
2.2/2.0
1
2.22-1.1
1.12
^C
(interrupt) use quit to exit.
exit
0
^C
(interrupt) use quit to exit.
quit
xiao123@xiao123:~/Downloads/shscripts$

例子2

xiao123@xiao123:~/Downloads/shscripts$ num=5
xiao123@xiao123:~/Downloads/shscripts$ echo ${num}*5 | bc
25
xiao123@xiao123:~/Downloads/shscripts$

案例

计算出1-1000的总和
数学公式
1+2+3+4+…+100

xiao123@xiao123:~/Downloads/shscripts$ echo {1..100}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
xiao123@xiao123:~/Downloads/shscripts$ #tr 替换
xiao123@xiao123:~/Downloads/shscripts$ echo {1..100} | tr " " "+" #方案1
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99+100
xiao123@xiao123:~/Downloads/shscripts$ seq -s "+" 100  #方案2
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99+100
xiao123@xiao123:~/Downloads/shscripts$
xiao123@xiao123:~/Downloads/shscripts$ echo {1..100} | tr " " "+" | bc
5050
xiao123@xiao123:~/Downloads/shscripts$
xiao123@xiao123:~/Downloads/shscripts$ echo $((`echo {1..100} | tr " " "+"`))
5050
xiao123@xiao123:~/Downloads/shscripts$
xiao123@xiao123:~/Downloads/shscripts$ seq -s " + " 100 | xargs expr
5050
xiao123@xiao123:~/Downloads/shscripts$
awk计算

awk支持小数计算。

xiao123@xiao123:~/Downloads/shscripts$ seq -s " + " 100 | xargs expr
5050
xiao123@xiao123:~/Downloads/shscripts$ echo "2.2" "3.0" | awk '{print $1*$2}'
6.6
xiao123@xiao123:~/Downloads/shscripts$ echo "2.2" "3.0" | awk '{print ($1*$2)}'
6.6
xiao123@xiao123:~/Downloads/shscripts$ echo "2.2" "3.0" | awk '{print ($1*$2)+4}'
10.6
xiao123@xiao123:~/Downloads/shscripts$ echo "2.2" "3.0" | awk '{print $1*$2+4}'
10.6
xiao123@xiao123:~/Downloads/shscripts$
中括号计算

$[表达式]

xiao123@xiao123:~/Downloads/shscripts$ num=5
xiao123@xiao123:~/Downloads/shscripts$ res=$[num+4]
xiao123@xiao123:~/Downloads/shscripts$ echo ${res}
9
xiao123@xiao123:~/Downloads/shscripts$ res=$[num-4]
xiao123@xiao123:~/Downloads/shscripts$ echo ${res}
1
xiao123@xiao123:~/Downloads/shscripts$ res=$[num*4]
xiao123@xiao123:~/Downloads/shscripts$ echo ${res}
20
xiao123@xiao123:~/Downloads/shscripts$ res=$[num/4]
xiao123@xiao123:~/Downloads/shscripts$ echo ${res}
1
xiao123@xiao123:~/Downloads/shscripts$
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值