shell脚本案例

一、set命令实现脚本安全

bash 复制代码
[root@localhost ~]# set -o
allexport      	off
braceexpand    	off
emacs          	on
errexit        	off
errtrace       	off
functrace      	off
hashall        	on
histexpand     	on
history        	on
ignoreeof      	off
interactive-comments	on
keyword        	off
monitor        	on
noclobber      	off
noexec         	off
noglob         	off
nolog          	off
notify         	off
nounset        	off
onecmd         	off
physical       	off
pipefail       	off
posix          	off
privileged     	off
verbose        	off
vi             	off
xtrace         	off
[root@localhost ~]# vim shell/error.sh
#!/bin/bash
echo "Hello World"
sssss
echo "Hello Linux"
[root@localhost ~]# chmod +x shell/error.sh 
[root@localhost ~]# shell/error.sh 
Hello World
shell/error.sh:行3: sssss: 未找到命令
Hello Linux
[root@localhost ~]# vim shell/error.sh
#!/bin/bash
set -e
echo "Hello World"
sssss
echo "Hello Linux"
[root@localhost ~]# shell/error.sh 
Hello World
shell/error.sh:行4: sssss: 未找到命令

二、通过代码演示一下三种形式的区别

bash 复制代码
#!/bin/bash
n=74
str1=c.biancheng.net$n 
str2="shell \"Script\" $n"
str3='C语言中文网 $n'
echo $str1
echo $str2
echo $str3


# 运行结果
c.biancheng.net74
shell "Script" 74
C语言中文网 $n

三、Shell字符串拼接

bash 复制代码
#!/bin/bash
name="shell"
url="http://c.biancheng.net/shell/"
str1=$name$url #中间不能有空格
str1=$name":"$url
str2="$name $url" #如果被双引号包围,那么中间可以有空格,也可以出现别的字符串
str3="$name:$url" 
str4="${name}Script:${url}Index.html" #在变量后加上字符串,需要给变量名加上大括号

四、常用转义字符

bash 复制代码
[root@localhost ~]# printf "%s\n" 1 2 3 4
1
2
3
4
[root@localhost ~]# printf "%f\n" 1 2 3 4
1.000000
2.000000
3.000000
4.000000
[root@localhost ~]# printf "%.2f\n" 1 2 3 4 #.2f表示保留两位小数
1.00
2.00
3.00
4.00 
[root@localhost ~]# printf "(%s)" 1 2 3 4;echo " "
(1)(2)(3)(4) 
[root@localhost ~]# printf " (%s) " 1 2 3 4;echo " "
 (1)  (2)  (3)  (4)  
[root@localhost ~]# printf " (%s) (%s)\n" 1 2 3 4;echo " "
 (1) (2)
 (3) (4)
[root@localhost ~]# printf " %s %s\n" 1 2 3 4;echo " "
 1 2
 3 4
[root@localhost ~]# printf "%s %s %s\n" 1 2 3 4
1 2 3
4  
[root@localhost ~]# 

#%-10s表示宽度10个字符,左对齐
[root@localhost ~]# printf "%-10s %-10s %-4s %s \n" 姓名 性别 年龄 体重 小明 男性 20岁 70KG 小红 女性 18岁 50KG 
姓名     性别     年龄 体重 
小明     男性     20岁 70KG 
小红     女性     18岁 50KG 
[root@localhost ~]# 


#将十进制的1000转换为16进制数
[root@localhost ~]# printf "%X\n" 1000
3E8
[root@localhost ~]# printf "%x\n" 1000
3e8
[root@localhost ~]# 

#将十六进制的C转换为十进制
[root@localhost ~]# printf "%d\n" 0xc
12
[root@localhost ~]# 


[root@localhost ~]# var="welcome to study";printf "\033[31m%s\033[0m\n" $var
welcome
to
study
[root@localhost ~]# var="welcome to study";printf "\033[31m%s\033[0m\n" "$var"
welcome to study
[root@localhost ~]#

五、使用bc计算小数和declare -i计算

bash 复制代码
[root@localhost ~]# echo "scale=3;20/3"|bc
6.666
[root@localhost ~]# echo "scale=3;2/3"|bc
.666
[root@localhost ~]# i=20
[root@localhost ~]# j=20
[root@localhost ~]# declare -i sum=i*j
[root@localhost ~]# echo $sum
400
[root@localhost ~]# 

六、生成0-49之间的随机数

bash 复制代码
[root@localhost ~]# echo $[$[$RANDOM%50]+1]
40
[root@localhost ~]# echo $[$RANDOM%50]
44
[root@localhost ~]# echo $[$[$RANDOM%50]+1]  #生成1~50之间的随机数
[root@localhost ~]# echo $[RANDOM % 100 + 1]

七、生成随机颜色字符串

bash 复制代码
[root@localhost ~]# echo -e "\033[1;$[RANDOM%7+31]mStudy\033[0m"
Study
[root@localhost ~]# echo -e "\033[1;$[RANDOM%7+31]mStudy\033[0m"
Study
[root@localhost ~]#

八、鸡兔同笼问题

bash 复制代码
[root@localhost ~]# vim shell/chicken.sh
#!/bin/bash
HEAD=35
FOOT=94

RABBIT=$(((FOOT-HEAD-HEAD)/2))
CHOOK=$[35-RABBIT]
echo "兔子的数量为:"$RABBIT
echo "鸡的数量为: "$CHOOK
                           
[root@localhost ~]# chmod +x shell/chicken.sh 
[root@localhost ~]# shell/chicken.sh 
兔子的数量为::12
鸡的数量为:23
[root@localhost ~]# 

# 在脚本中写入变量,让用户在命令行写入需要计算的数值
[root@localhost ~]# vim shell/chicken.sh
#!/bin/bash
HEAD=$1
FOOT=$2

RABBIT=$(((FOOT-HEAD-HEAD)/2))
CHOOK=$[HEAD-RABBIT]
echo "兔子的数量为:"$RABBIT
echo "鸡的数量为: "$CHOOK
          
[root@ansible-salve1 ~]# ./chicken.sh 30 80
兔子的数量为:10
鸡的数量为: 25
[root@ansible-salve1 ~]# 

九、计算出所有人的年龄总和

bash 复制代码
[root@ansible-salve1 shell]# vim nianling.txt
[root@ansible-salve1 shell]# cat nianling.txt
a=20
b=18
c=22
[root@ansible-salve1 shell]# cut -d"=" -f2 nianling.txt 
20
18
22
[root@ansible-salve1 shell]# cut -d"=" -f2 nianling.txt | tr '\n' + | grep -Eo ".*[0-9]" | bc
60
[root@ansible-salve1 shell]# grep -Eo "[0-9]+" nianling.txt 
20
18
22
[root@ansible-salve1 shell]# grep -Eo "[0-9]+" nianling.txt | tr '\n' +| grep -Eo ".*[0-9]" | bc
60
[root@ansible-salve1 shell]# 

十、文件测试表达式

bash 复制代码
[root@ansible-salve1 ~]# test -a test.txt
[root@ansible-salve1 ~]# echo $?
1
[root@ansible-salve1 ~]# test -d shell
[root@ansible-salve1 ~]# echo $?
0
[root@ansible-salve1 ~]# touch test.txt
[root@ansible-salve1 ~]# test -w test.txt &&echo  "true"
true
[root@ansible-salve1 ~]# test -r test.txt &&echo  "true"
true
[root@ansible-salve1 ~]# test -x test.txt &&echo  "true"
[root@ansible-salve1 ~]# 

十一、测试字符串

bash 复制代码
[root@ansible-salve1 ~]# var_test='Mike' 
[root@ansible-salve1 ~]# echo $var_test 
Mike
[root@ansible-salve1 ~]# [[ -n var_test ]] && echo "True"
True

# 通配符
[root@ansible-salve1 ~]# FILE=test.log
[root@ansible-salve1 ~]# [[ "$FILE" == *.log ]] && echo "True"
True
[root@ansible-salve1 ~]# FILE=test.txt
[root@ansible-salve1 ~]# [[ "$FILE" == *.log ]] && echo "True"
[root@ansible-salve1 ~]# [[ "$FILE" != *.log ]] && echo "True"
True
[root@ansible-salve1 ~]# 

# 扩展的正则表达式
[root@ansible-salve1 ~]# FILE=test.log
[root@ansible-salve1 ~]# [[ "$FILE" =~  \.log$ ]] && echo "True"
True
[root@ansible-salve1 ~]# N=100
[root@ansible-salve1 ~]# [[ "$N" =~ ^[0-9]+$ ]] && echo "True"
True
[root@ansible-salve1 ~]# N=A10
[root@ansible-salve1 ~]# [[ "$N" =~ ^[0-9]+$ ]] && echo "True"
[root@ansible-salve1 ~]# IP=1.2.3.4
[root@ansible-salve1 ~]# [[ "$IP" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]
[root@ansible-salve1 ~]# echo $?
0
[root@ansible-salve1 ~]# 
# 使用正则表达式判断IP是否合法
[root@ansible-salve1 ~]# IP=1.2.3.333
[root@ansible-salve1 ~]# [[ $IP =~ ^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]]
[root@ansible-salve1 ~]# echo $?
1
[root@ansible-salve1 ~]# IP=255.255.255.255
[root@ansible-salve1 ~]# [[ $IP =~ ^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]]
[root@ansible-salve1 ~]# echo $?
0
[root@ansible-salve1 ~]# 

十二、磁盘空间的判断

bash 复制代码
# 查看磁盘空间占用率,若超出80则提示空间不足。
[root@localhost ~]# df | head -2 | tail -1 | tr -s ' ' | cut -d' ' -f5 | cut -d'%' -f1
5
[root@localhost ~]# used_precent=$(df | head -2 | tail -1 | tr -s ' ' | cut -d' ' -f5 | cut -d'%' -f1)
[root@localhost ~]# echo $used_precent
5
[root@localhost ~]# [ $used_precent -gt 80 ] && echo "磁盘空间不足!" || echo "磁盘空间充足!"
磁盘空间充足!

十三、使用read给多个变量赋值并输出

bash 复制代码
[root@ansible-salve1 shell]# vim info.sh 
#!/bin/bash
read -p "Enter some information > " name url age
echo "网站名字:$name"
echo "网址:$url"
echo "年龄:$age"
[root@ansible-salve1 shell]# chmod +x info.sh 
[root@ansible-salve1 shell]# ./info.sh 
Enter some information > hehao www.baidu.com 18
网站名字:hehao
网址:www.baidu.com
年龄:18
[root@ansible-salve1 shell]# 

# 注意:必须在一行内输入所有的值,不能换行,否则只能给第一个变量赋值,后续变量都会赋值失败

十四、只读取一个字符

bash 复制代码
# -n 1表示只读取一个字符,运行脚本后,只要用户输入一个字符,立即就读取结束,不等待用户按下回车键
[root@ansible-salve1 shell]# vim info1.sh 
#!/bin/bash
read -n 1 -p "Enter a char > " char  && printf "\n"
echo "---------------------------------------------------------"
echo $char
[root@ansible-salve1 shell]# chmod +x info1.sh 
[root@ansible-salve1 shell]# ./info1.sh 
Enter a char > a
---------------------------------------------------------
a

十五、在指定时间内输入密码

bash 复制代码
#使用&&组合了多个命令,这些命令会依次执行,并且从整体上作为 if 语句的判断条件,只要其中一个命令执行失败(退出状态为非 0 值),整个判断条件就失败了,后续的命令也就没有必要执行
[root@ansible-salve1 shell]# vim info2.sh
#!/bin/bash
if
    read -t 20 -sp "Enter password in 20 seconds(once) > " pass1 && printf "\n" &&  #第一次输入密码
    read -t 20 -sp "Enter password in 20 seconds(again)> " pass2 && printf "\n" &&  #第二次输入密码
    [ $pass1 == $pass2 ]  #判断两次输入的密码是否相等
then
    echo "Valid password"
else
    echo "Invalid password"
fi
[root@ansible-salve1 shell]# chmod +x info2.sh 
[root@ansible-salve1 shell]# ./info2.sh 
Enter password in 20 seconds(once) > 
Enter password in 20 seconds(again)> 
Valid password
[root@ansible-salve1 shell]# 

十六、利用正则表达式

bash 复制代码
[root@ansible-salve1 shell]# vim info3.sh
[root@ansible-salve1 shell]# cat info3.sh 
#!/bin/bash
read -p "Are you rich? yes or no: " ANSWER
[[ $ANSWER =~ ^[Yy]|[Yy][Ee][Ss]$ ]] && echo "You Are Rich" || echo "Good Good Study,Day Day up"
[root@ansible-salve1 shell]# chmod +x info3.sh 
[root@ansible-salve1 shell]# ./info3.sh 
Are you rich? yes or no: y
You Are Rich
[root@ansible-salve1 shell]# ./info3.sh 
Are you rich? yes or no: YeS
You Are Rich
[root@ansible-salve1 shell]# 

十七、工作选项

bash 复制代码
[root@ansible-salve1 shell]# vim backup.sh 
#!/bin/bash
SRC=/etc/
DEST=/data/backup_`date +%F_%H-%M-%S`
cp -a $SRC $DEST
[ $? -eq 0 ] && echo "备份成功" || echo "备份失败"
[root@ansible-salve1 shell]# chmod +x backup.sh
[root@ansible-salve1 shell]# vim info4.sh
#!/bin/bash
cat <<EOF
请选择:
1.备份文件
2.清理日志文件
3.软件升级
4.软件回滚
5.删库跑路
EOF
read -p "请输入上面的数字1-5:" MENU
[ $MENU -eq 1 ] && ./backup.sh
[ $MENU -eq 2 ] && echo "清理日志文件"
[ $MENU -eq 3 ] && echo "软件升级"
[ $MENU -eq 4 ] && echo "软件回滚"
[ $MENU -eq 5 ] && echo "删除跑路"

[root@ansible-salve1 shell]# chmod +x info4.sh 
[root@ansible-salve1 shell]# ./info4.sh 
请选择:
1.备份数据库
2.清理日志文件
3.软件升级
4.软件回滚
5.删库跑路
请输入上面的数字1-5:1
备份成功
[root@ansible-salve1 shell]# 
相关推荐
无敌的牛14 小时前
网络通信IP细节
服务器·网络·tcp/ip
b***251114 小时前
电动车动力电池自动点焊机|深圳比斯特自动化
运维·自动化
wb18914 小时前
CICD的持续集成与持续交付和Zabbix
运维·笔记·ci/cd·云计算·zabbix
倔强的石头_14 小时前
【Linux指南】冯诺依曼体系结构:现代计算机的基石
linux
敲上瘾15 小时前
Docker镜像指南:从核心命令到离线迁移实战
linux·运维·docker·容器·架构
Blessed_Li15 小时前
Higress云原生API网关详解 与 Linux版本安装指南
linux·运维·云原生·higress
EchoSam15 小时前
【Linux笔记】命令行与vim基础
linux·笔记·vim
友恒15 小时前
两台电脑通过网线直连共享数据,设置正确,却互相ping不通的解决方法
服务器
礼拜天没时间.15 小时前
Rsync + Rsyncd 从入门到项目实战:自动化备份全攻略
linux·centos·rsync·文件传输·rsyncd