失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > shell脚本练习-课后练习

shell脚本练习-课后练习

时间:2024-06-09 06:20:44

相关推荐

shell脚本练习-课后练习

SHELL脚本编程课后练习

一.1、编写脚本 systeminfo.sh,显示当前主机系统信息,包括:主机名,IPv4地址,操作系统版本,内核2、编写脚本 backup.sh,可实现每日将/etc/目录备份到/backup/etcYYYY-mm-dd中3、编写脚本 disk.sh,显示当前硬盘分区中空间利用率最大的值4、编写脚本 links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排二.1、编写脚本 argsnum.sh,接受一个文件路径作为参数;如果参数个数小于1,则提示用户“至少应该给2、编写脚本 hostping.sh,接受一个主机的IPv4地址做为参数,测试是否可连通。如果能ping通,则提示用户“该IP地址可访问”;如果不可ping通,则提示用户“该IP地址不可访问”3、编写脚本 checkdisk.sh,检查磁盘分区空间和inode使用率,如果超过80%,就发广播警告空间将满4、编写脚本 per.sh,判断当前用户对指定参数文件,是否不可读并且不可写5、编写脚本 excute.sh ,判断参数文件是否为sh后缀的普通文件,如果是,添加所有人可执行权限,否则提示用户非脚本文件6、编写脚本 nologin.sh和 login.sh,实现禁止和允许普通用户登录系统三.1、让所有用户的PATH环境变量的值多出一个路径,例如:/usr/local/apache/bin2、用户 root 登录时,修改命令提示符颜色,设置命令别名3、任意用户登录系统时,显示红色字体的警示提醒信息“Hi,dangerous!”4、编写生成脚本基本格式的脚本,包括作者,联系方式,版本,时间,描述等四.1、编写脚本 createuser.sh2、编写脚本 yesorno.sh,提示用户输入yes或no,并判断用户输入的是yes还是no,或是其它信息3、编写脚本 filetype.sh,判断用户输入文件路径,显示其文件类型(普通,目录,链接,其它文件类型)4、编写脚本 checkint.sh,判断用户输入的参数是否为正整数5、编写脚本 reset.sh,五. for循环练习1. 判断/var/目录下所有文件的类型2.添加10个用户user1-user10,密码为8位随机字符3./etc/rc.d/rc3.d目录下分别有多个以K开头和以S开头的文件;分别读取每个文件,以K开头的输出为文件名加stop,以S开通的输出为文件名加start,如K34filename stop S66filename start4.编写脚本,提示输入正整数n的值,计算1+2+...+n的总和5.计算100以内所有能被3整除的整数之和6.编写脚本,提示输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态7.打印9x9乘法表8.在/testdir目录下创建10个html文件,文件名格式为数字N(从1到10)加随机8个字母,如:1AbCdeFgH.html9.打印等腰三角形10.猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半加一个。到第10天早上想再吃时,只剩下一个桃子了。求第一天共摘了多少?11.鸡兔同笼算法,今有雉兔同笼,上有三十五头,下有九十四足,问雉兔各几何?12.选择输入yes or nofor循环总结六. while循环1、编写脚本,求100以内所有正奇数之和2、编写脚本,提示请输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态,并统计在线和离线主机各多少3、编写脚本,打印九九乘法表4、编写脚本,利用变量RANDOM生成10个随机数字,输出这个10数字,并显示其中的最大值和最小值5、编写脚本,实现打印国际象棋棋盘6、破解这些字符串对应的RANDOM值七. 循环控制continue,break,shift1、每隔3秒钟到系统上获取已经登录的用户的信息;如果发现用户hacker登录,则将登录时间和主机记录于日志/var/log/login.log中,并退出脚本2、随机生成10以内的数字,实现猜字游戏,提示比较大或小,相等则退出3、用文件名做为参数,统计所有参数文件的总行数4、用二个以上的数字为参数,显示其中的最大值和最小值八. 函数1.编写函数,实现OS的版本判断2. 编写函数,实现取出当前系统eth0的IP地址3. 编写函数,实现打印绿色OK和红色FAILED4. 编写函数,实现判断是否无位置参数,如无参数,提示错误5. 编写函数,实现两个数字做为参数,返回最大值6. 编写服务脚本/root/bin/testsrv.sh,完成如下要求(1) 脚本可接受参数:start, stop, restart, status7. 编写脚本/root/bin/copycmd.sh8. 斐波那契数列又称黄金分割数列,因数学家列昂纳多·斐波那契以兔子繁殖为例子而引入,故又称9. 汉诺塔(又称河内塔)九. 数组1. 输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序2. 将下图所示,实现转置矩阵 matrix.sh3. 打印杨辉三角形十.expect的应用

一.

1、编写脚本 systeminfo.sh,显示当前主机系统信息,包括:主机名,IPv4地址,操作系统版本,内核

版本,CPU型号,内存大小,硬盘大小

[root@centos8 script]#cat system_info.sh #!/bin/bashRED="\E[1;31m"GREEN="echo -e \E[1;32m"END="\E[0m"$GREEN----------------------Host systeminfo--------------------$ENDecho -e "HOSTNAME:$RED`hostname`$END"#echo -e "IPADDR: $RED` ifconfig eth0|grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' |head -n1`$END"echo -e "IPADDR: $RED` hostname -I`$END"echo -e "OSVERSION: $RED`cat /etc/redhat-release`$END"echo -e "KERNEL: $RED`uname -r`$END"echo -e "CPU: $RED`lscpu|grep 'Model name'|tr -s ' '|cut -d : -f2`$END"echo -e "MEMORY: $RED`free -h|grep Mem|tr -s ' ' : |cut -d : -f2`$END"echo -e "DISK: $RED`lsblk |grep '^sd' |tr -s ' ' |cut -d " " -f4`$END"$GREEN---------------------------------------------------------$END#颜色设定random_num=$[$RANDOM%7+31]echo -e "\033[1;${random_num}m${random_num}\033[0m"

2、编写脚本 backup.sh,可实现每日将/etc/目录备份到/backup/etcYYYY-mm-dd中

[root@centos8 script]#cat backup.sh#!/bin/bashcp -r /etc/* /backup/etc`date +%Y-%m-%d`[root@centos8 script]#vim /etc/crontabSHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=root# For details see man 4 crontabs# Example of job definition:# .---------------- minute (0 - 59)# | .------------- hour (0 - 23)# | | .---------- day of month (1 - 31)# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# | | | | |# * * * * * user-name command to be executed30 1 * * * /usr/bin/bash /root/script/backup.sh

3、编写脚本 disk.sh,显示当前硬盘分区中空间利用率最大的值

#!/bin/bashecho `df | grep 'sda' |tr -s " " % |cut -d% -f5|sort -nr | head -n1`

4、编写脚本 links.sh,显示正连接本主机的每个远程主机的IPv4地址和连接数,并按连接数从大到小排

#!/bin/bashlast | grep '^root' | tr -s " "|cut -d " " -f3 |sort|uniq -c

二.

1、编写脚本 argsnum.sh,接受一个文件路径作为参数;如果参数个数小于1,则提示用户“至少应该给

一个参数”,并立即退出;如果参数个数不小于1,则显示第一个参数所指向的文件中的空白行数

[root@centos8 script]#cat argsnum.sh#!/bin/bash[ -z $1 ] && echo 至少应该给一个参数 || grep '^$' $1 |wc -l[root@centos8 script]#bash argsnum.sh /etc/crontab3

2、编写脚本 hostping.sh,接受一个主机的IPv4地址做为参数,测试是否可连通。如果能ping通,则提示用户“该IP地址可访问”;如果不可ping通,则提示用户“该IP地址不可访问”

[root@centos8 script]#cat hostping.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-14#FileName: hostping.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************read -p "请输入一个IP地址:" ip[ -z $ip ] && {echo "输入有误,请重新输入" ;exit; } || {ping -c1 -w1 $ip > /dev/null && echo 该IP地址可访问 || echo 该IP地址不可访问 ; }[root@centos8 script]#bash hostping.sh 请输入一个IP地址:输入有误,请重新输入[root@centos8 script]#bash hostping.sh 请输入一个IP地址:10.0.0.188该IP地址不可访问[root@centos8 script]#bash hostping.sh 请输入一个IP地址:10.0.0.2 该IP地址可访问

3、编写脚本 checkdisk.sh,检查磁盘分区空间和inode使用率,如果超过80%,就发广播警告空间将满

[root@centos8 script]#vim check_disk2.sh #!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-14#FileName: check_disk2.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************inode=`df -i |sed -nr 's@\/dev\/sd.* ([0-9]+)% .*@\1@p' |sort -nr |head -n1`space=`df |sed -nr 's@\/dev\/sd.* ([0-9]+)% .*@\1@p' |sort -nr |head -n1`WARNING=80if [ $inode -gt $WARNING ];thenecho "Disk inodes used $inode%,it will be full" | mail -s "disk warning" 1589640561@fiif [ $space -gt $WARNING ];thenecho "Disk spaces used $inode%,it will be full" | mail -s "disk warning" 1589640561@fi

4、编写脚本 per.sh,判断当前用户对指定参数文件,是否不可读并且不可写

[root@centos8 script]#cat per.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-14#FileName: per.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************read -p "请输入文件路径:" fpath#fpath=/root/script/perfile.txt[ -z $fpath ] && {echo "输入的文件路径有误,请重新输入" ;eixt; }username=`whoami`#写法1[ ! -r $fpath ] && [ ! -w $fpath ] && echo "1 $username 对该文件不可读且不可写"#写法2[ ! -r $fpath -a ! -w $fpath ] && echo "2 $username 对该文件没有读写权限"[root@centos8 script]#ll /root/script/perfile.txt-rw-r----- 1 root root 0 Jul 14 22:41 /root/script/perfile.txt[root@centos8 script]#bash per.sh 请输入文件路径:/root/script/perfile.txt[liudh@centos8 ~]$bash /root/script/per.sh请输入文件路径:/root/script/perfile.txt1 liudh 对该文件不可读且不可写2 liudh 对该文件没有读写权限

5、编写脚本 excute.sh ,判断参数文件是否为sh后缀的普通文件,如果是,添加所有人可执行权限,否则提示用户非脚本文件

[root@centos8 practise练习]#vim excute.sh#!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-15#FileName: excute.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************#read -p "请输入检测文件的路径:" FILEFILE=/root/script/hello_word.sh[ `ls $FILE |grep '.*.sh$'` ] && {chmod a+x $FILE;ls -l $FILE; } || echo "$FILE is not a script file "

6、编写脚本 nologin.sh和 login.sh,实现禁止和允许普通用户登录系统

[root@centos8 script]#vim login_choice.sh##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-15#FileName: login_choice.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************read -p "请选择禁止或允许用户$1登录系统(yes/no):" choicechoice=`echo $choice |tr "A-Z" "a-z"`case $choice iny|yes)usermod -s /bin/bash $1echo "已允许用户$1登录系统";;n|no)usermod -s /sbin/nologin $1echo "已禁止用户$1登录系统";;*)echo "输入有误,请重新输入"exit;;esac[root@centos8 script]#bash login_choice.sh liudh请选择禁止或允许用户liudh登录系统(yes/no):n已禁止用户liudh登录系统[root@centos8 script]#getent passwd | grep liudhliudh:x:1000:1000::/home/liudh:/sbin/nologin[root@centos8 script]#bash login_choice.sh liudh请选择禁止或允许用户liudh登录系统(yes/no):Y 已允许用户liudh登录系统

三.

1、让所有用户的PATH环境变量的值多出一个路径,例如:/usr/local/apache/bin

[root@centos8 ~]#vim /etc/profile.d/editPATH.sh#!/bin/bashPATH="$PATH:/usr/local/apache/bin"[root@centos8 ~]#source /etc/profile.d/editPATH.sh[root@centos8 ~]#echo $PATH/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin:/usr/local/apache/bin

2、用户 root 登录时,修改命令提示符颜色,设置命令别名

将命令指示符变成红色,并自动启用如下别名: rm=‘rm -i’

cdnet=‘cd /etc/sysconfig/network-scripts/’

editnet=‘vim /etc/sysconfig/network-scripts/ifcfg-eth0’

editnet=‘vim /etc/sysconfig/network-scripts/ifcfg-eno16777736 或 ifcfg-ens33 ’ (如果系统是CentOS7)

[root@centos8 practise练习]#vim setrootlogin.sh#!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-15#FileName: setrootlogin.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************[ ! `whoami` = root ] && echo "You are not root" && exitcat >>~/.bashrc <<EOF PS1='\[\e[1;31m\][\u@\h \W]\\$ \[\e[0m\]'alias rm='rm -i'alias cdnet='cd /etc/sysconfig/network-scripts'alias editnet='vim /etc/sysconfig/network-scripts/ifcfg-eth0'EOF

3、任意用户登录系统时,显示红色字体的警示提醒信息“Hi,dangerous!”

[root@centos8 script]#cat logintips.sh #!/bin/bashcat >> ~/.bash_profile <<EOFecho -e '\E[1;31mHi,dangerous!\E[0m'EOF

4、编写生成脚本基本格式的脚本,包括作者,联系方式,版本,时间,描述等

[root@centos8 ~]#cat .vimrcset ts=4set expandtabset ignorecaseautocmd BufNewFile *.sh exec ":call SetTitle()"func SetTitle()if expand("%:e") == 'sh'call setline(1,"#!/bin/bash")call setline(2,"#")call setline(3,"#********************************************************************")call setline(4,"#Author:LingXia")call setline(5,"#QQ:1589640561")call setline(6,"#Date: ".strftime("%Y-%m-%d"))call setline(7,"#FileName: ".expand("%"))call setline(8,"#URL: /weixin_41142408")call setline(9,"#Description:The test script")call setline(10,"#Copyright (C): ".strftime("%Y")." All rights reserved")call setline(11,"#********************************************************************")call setline(12,"")endifendfuncautocmd BufNewFile * normal G

四.

1、编写脚本 createuser.sh

实现如下功能:使用一个用户名做为参数,如果指定参数的用户存在,就显示其存在,否则添加之。并设置初始密码为123456,显示添加的用户的id号等信息,在此新用户第一次登录时,会提示用户立即改密码,如果没有参数,就提示:请输入用户名

[root@centos8 script]#vim creaeuser.sh#!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-15#FileName: creaeuser.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************[ -z $1 ] && echo "请输入需要创建的用户名,expr:$0 hehe" && exitid $1 &> /dev/null && echo "user $1 exist" && exituseradd $1echo "123456" |passwd --stdin $1 > /dev/nullid $1echo "$1 is created"[root@centos8 script]#bash creaeuser.sh doudouuid=1008(doudou) gid=1011(doudou) groups=1011(doudou)doudou is created[root@centos8 script]#bash creaeuser.sh rootuser root exist[root@centos8 script]#bash creaeuser.sh请输入需要创建的用户名,expr:creaeuser.sh hehe

2、编写脚本 yesorno.sh,提示用户输入yes或no,并判断用户输入的是yes还是no,或是其它信息

[root@centos8 script]#cat bookmark/yesorno_case_tr.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -06-18#FileName: case_yesorno.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************read -p "Are you OK (Yes/No) ?" answeranswer=`echo $answer |tr "A-Z" "a-z"`case $answer iny|yes)echo "Yes";;n|no)echo "No";;*)echo "You input is error";;esac

3、编写脚本 filetype.sh,判断用户输入文件路径,显示其文件类型(普通,目录,链接,其它文件类型)

[root@centos8 script]#cat for/for_test_filetype.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -06-21#FileName: test_file.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************read -p "请输入完整的目录路径:" DIR[ ! -z "${DIR}" ] && [ -d ${DIR} ] || {echo "You input is false,please check it !" ; exit; }echo "The directory is ${DIR}"cd ${DIR}for file in `ls ${DIR}` ;doif [ -d "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Directory"elif [ -L "${file}" ];then#如果先检查普通文件后再检查链接文件,链接文件会被识别为普通文件echo -e "${DIR}/${file} \t \t \t \t Symbolic Link"elif [ -f "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Regular File"elif [ -b "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Block Special"elif [ -c "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t character special"else echo "${DIR}/${file} \t \t \t \t Unknow"fidone[root@centos8 script]#bash for/for_test_filetype.sh请输入完整的目录路径:/dataThe directory is /data/data/118580365Regular File/data/checkfiletype.shSymbolic Link/data/logsDirectory/data/mysqlDirectory/data/scriptDirectory/data/snap[root@centos8 script]#cat for/for_test_filetype2.sh#!/bin/bashread -p "请输入完整的目录路径:" DIR[ ! -z "${DIR}" ] && [ -d ${DIR} ] || {echo "You input is false,please check it !" ; exit; }echo "The directory is ${DIR}"cd ${DIR}for file in `ls ${DIR}` ;doif [ -d "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Directory" elif [ -f "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Regular File"elif [ -L "${file}" ];then#如果先检查普通文件后再检查链接文件,链接文件会被识别为普通文件echo -e "${DIR}/${file} \t \t \t \t Symbolic Link"elif [ -b "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Block Special"elif [ -c "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t character special"else echo "${DIR}/${file} \t \t \t \t Unknow"fidone[root@centos8 script]#bash for/for_test_filetype.sh请输入完整的目录路径:/dataThe directory is /data/data/118580365Regular File/data/checkfiletype.shRegular File/data/logsDirectory/data/mysqlDirectory/data/scriptDirectory/data/snapDirectory[root@centos8 script]#ll /datatotal 124K-rw-r--r-- 1 root admins 121K Jul 13 16:35 118580365lrwxrwxrwx 1 root admins 37 Jul 15 18:27 checkfiletype.sh -> /root/script/for/for_test_filetype.shdrwxr-sr-x 2 root admins 6 Jul 15 18:23 logsdrwxr-sr-x 2 root admins 6 Jul 11 13:04 mysqllrwxrwxrwx 1 root admins 12 Jul 15 18:25 script -> /root/scriptdrwxr-sr-x 2 root admins 6 Jul 12 19:37 snap#估计目录链接也是如此[root@centos8 script]#vim for/for_test_filetype.sh#!/bin/bashread -p "请输入完整的目录路径:" DIR[ ! -z "${DIR}" ] && [ -d ${DIR} ] || {echo "You input is false,please check it !" ; exit; }echo "The directory is ${DIR}"cd ${DIR}for file in `ls ${DIR}` ;doif [ -L "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Symbolic Link"elif [ -d "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Directory"elif [ -f "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Regular File"elif [ -b "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t Block Special"elif [ -c "${file}" ];thenecho -e "${DIR}/${file} \t \t \t \t character special"else echo "${DIR}/${file} \t \t \t \t Unknow"fidone[root@centos8 script]#bash for/for_test_filetype.sh请输入完整的目录路径:/dataThe directory is /data/data/118580365Regular File/data/checkfiletype.shSymbolic Link/data/logsDirectory/data/mysqlDirectory/data/scriptSymbolic Link/data/snapDirectory

是否可以得出这样的结论:判断文件类型时,尽量将目录和普通文件的判断放在最后

4、编写脚本 checkint.sh,判断用户输入的参数是否为正整数

[root@centos8 script]#cat checkint.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-15#FileName: checkint.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************read -p "请输入一个正整数:" necho -e "第一种写法输出信息:\c"if [[ "$n" =~ ^[1-9]+[0-9]+$ ]] ;then #注:使用=~判断事需要两对中括号,且变量要加双引号作字符处理echo "输入正确"else echo "输入错误"fi#这么写在判断00001 这样数的时候也会提示错误#bug写法#[[ "$n" =~ ^[1-9]+$ ]]#[[ "$n" =~ ^[1-9]+[0-9]$ ]]echo -e "第二种写法输出信息:\c"if [[ "$n" =~ ^[0-9]+$ ]];thenif [ $n -eq 0 ];thenecho "0 不是正整数,输入错误"elseecho "输入正确"fielseecho "输入错误"fi[root@centos8 script]#bash checkint.sh请输入一个正整数:01第一种写法输出信息:输入错误第二种写法输出信息:输入正确[root@centos8 script]#bash checkint.sh请输入一个正整数:0第一种写法输出信息:输入错误第二种写法输出信息:0 不是正整数,输入错误

5、编写脚本 reset.sh,

实现系统安装后的初始化环境,包括:1、别名 2、环境变量,如PS1等 3、安装常用软件包,如:tree 5、实现固定的IP的设置,6、vim的设置等

[root@centos8 select]#vim select_init.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-21#FileName: select_init.sh#URL: /weixin_41142408#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-21#FileName: select_init.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#FileName: select_init.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************echo -e "\e[$[$RANDOM%7+31];1m"PS3="请选择(1-7):"select choisce in 别名 环境变量PS1 安装常用软件 配置固定IP vim创建sh后缀文件初始化 history显示内容添加时间 退出该菜单;docase $REPLY in1)echo "设置常用命令别名";;2)echo "设置PS1";;3)echo "开始安装常用软件";;4)echo "配置固定IP";;5)echo "配置vim初始化文件";;6)echo "修改history显示内容";;7)break;;*)echo "输入有误,请重新选择(1-7)";;esacdoneecho -e "\e[0m"[root@centos8 select]#bash select_init.sh 1) 别名 5) vim创建sh后缀文件初始化2) 环境变量PS1 6) history显示内容添加时间3) 安装常用软件 7) 退出该菜单4) 配置固定IP请选择(1-7):7[root@centos8 select]#

五. for循环练习

1. 判断/var/目录下所有文件的类型

[root@centos8 script]#cat for_test_filetype.sh#!/bin/bashread -p "请输入完整的目录路径:" DIR[ ! -z "${DIR}" ] && [ -d ${DIR} ] || {echo "You input is false,please check it !" ; exit; }echo "The directory is ${DIR}"{cd ${DIR}for file in `ls ${DIR}` ;doif [ -d "${file}" ];thenecho -e "${DIR}/${file} \t\t Directory"elif [ -f "${file}" ];thenecho -e "${DIR}/${file} \t\t Regular File"elif [ -L "${file}" ];thenecho -e "${DIR}/${file} \t\t Symbolic Link"elif [ -b "${file}" ];thenecho -e "${DIR}/${file} \t\t Block Special"elif [ -c "${file}" ];thenecho -e "${DIR}/${file} \t\t character special"else echo "${DIR}/${file} \t\t Unknow"fidone}[root@centos8 script]#sh for_test_filetype.sh 请输入完整的目录路径:/devThe directory is /dev#只复制了一部分过来/dev/autofs character special/dev/blockDirectory/dev/cdromSymbolic Link/dev/charDirectory/dev/coreRegular File/dev/cpuDirectory/dev/fullcharacter special/dev/sda4Block Special/dev/sda5Block Special/dev/sg0character special/dev/sg1character special/dev/shmDirectory/dev/snapshot character special/dev/sndDirectory/dev/sr0Block Special/dev/stderr Symbolic Link/dev/stdinSymbolic Link

2.添加10个用户user1-user10,密码为8位随机字符

编写思想参考了CSDN用户lanyun_zhang的代码

重点1:随机字符,cat /dev/urandom |tr -dc ‘[:alnum:]’ |head -c8

重点2:命令chpasswd(批量更新用户口令工具)的使用方法

[root@centos8 script]#cat for_random_pwd.sh#!/bin/bashchpwdfile="/root/script/chpwdfile"for uid in {1..10};douseradd user$uidrchar=`cat /dev/urandom |tr -dc '[:alnum:]' |head -c8`echo "user$uid:$rchar" >> $chpwdfiledonechpasswd < $chpwdfile[root@centos8 script]#cat chpwdfile user1:HpA59OkEuser2:QyAHOGQ1user3:uNhGXiOguser4:dKIQJcV3user5:S3lNjZP2user6:oJ8ba545user7:VzeOtntpuser8:f6s4TaCAuser9:188dD4eFuser10:E15uhteB[root@centos8 script]#tail /etc/passwduser1:x:1001:1001::/home/user1:/bin/bashuser2:x:1002:1002::/home/user2:/bin/bashuser3:x:1003:1007::/home/user3:/bin/bashuser4:x:1004:1008::/home/user4:/bin/bashuser5:x:1005:1009::/home/user5:/bin/bashuser6:x:1006:1010::/home/user6:/bin/bashuser7:x:1007:1011::/home/user7:/bin/bashuser8:x:1008:1012::/home/user8:/bin/bashuser9:x:1009:1013::/home/user9:/bin/bashuser10:x:1010:1014::/home/user10:/bin/bash

3./etc/rc.d/rc3.d目录下分别有多个以K开头和以S开头的文件;分别读取每个文件,以K开头的输出为文件名加stop,以S开通的输出为文件名加start,如K34filename stop S66filename start

4.编写脚本,提示输入正整数n的值,计算1+2+…+n的总和

[root@centos8 script]#cat for_sum_n.sh#!/bin/bash#方法1,根据王老师代码修改read -p "input an integer:" nfor ((sum=0,i=1;i<=n;sum+=i,i++));dotruedoneecho $sum#方法2read -p "input an integer:" msum=0for i in `seq $m`;dolet sum+=idoneecho $sum[root@centos8 script]#sh for_sum_n.sh input an integer:1055input an integer:1005050

5.计算100以内所有能被3整除的整数之和

[root@centos8 script]#cat for_by3.sh#!/bin/bash#方法1sum=0for a in {3..100..3} ;dolet sum+=adoneecho $sum#方法2sum=0for i in {3..100};doa=$[i%3]if [ $a == 0 ];thensum=$[sum+i]fidoneecho $sum

6.编写脚本,提示输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态

[root@centos8 script]#cat for_ping_net.sh#!/bin/bash#不统计read -p "请输入要测试的网络地址,例如:192.168.0.0。network:" networkNET=`echo $network |sed 's/\.0$//g'`for ID in {51..60};doip=$NET.$IDping -c1 -W1 $ip > /dev/null && echo "$ip is up" || echo "$ip is down"done#有统计read -p "请输入要测试的网络地址,例如:192.168.0.0。network:" networkNET=`echo $network |sed 's/\.0$//g'`i=0;j=0for ID in {51..60};doip=$NET.$IDping -c1 -W1 $ip > /dev/null # echo $? if [ $? == 0 ];theni=$[i+1];echo $ip is up else j=$[j+1];echo $ip is downfidoneecho total $i hosts on-line,$j host off-line

执行结果

[root@centos8 script]#sh for_ping_net.sh请输入要测试的网络地址,例如:192.168.0.0。network:192.168.10.0192.168.10.51 is down192.168.10.52 is down192.168.10.53 is down192.168.10.54 is up192.168.10.55 is down192.168.10.56 is down192.168.10.57 is up192.168.10.58 is down192.168.10.59 is down192.168.10.60 is down请输入要测试的网络地址,例如:192.168.0.0。network:192.168.0.0192.168.0.51 is down192.168.0.52 is down192.168.0.53 is up192.168.0.54 is down192.168.0.55 is down192.168.0.56 is down192.168.0.57 is up192.168.0.58 is up192.168.0.59 is down192.168.0.60 is downtotal 3 hosts on-line,7 host off-line

7.打印9x9乘法表

[root@centos8 script]#cat for_product_list.sh #!/bin/bashfor i in {1..9};dofor j in `seq $i`;dolet product=$[i*j]echo -e "${j}x${i}=$product\t\c"doneechodone#执行结果[root@centos8 script]#bash for_product_list.sh 1x1=11x2=22x2=41x3=32x3=63x3=91x4=42x4=83x4=124x4=161x5=52x5=103x5=154x5=205x5=251x6=62x6=123x6=184x6=245x6=306x6=361x7=72x7=143x7=214x7=285x7=356x7=427x7=491x8=82x8=163x8=244x8=325x8=406x8=487x8=568x8=641x9=92x9=183x9=274x9=365x9=456x9=547x9=638x9=729x9=81

8.在/testdir目录下创建10个html文件,文件名格式为数字N(从1到10)加随机8个字母,如:1AbCdeFgH.html

重点:cat /dev/urandom |tr -dc ‘[:alpha:]’ |head -c8

[root@centos8 script]#cat bash for_10html.sh#!/bin/bashDIR=/data/testdirmkdir $DIRcd $DIRfor i in `seq 10` ;dord_char=`cat /dev/urandom |tr -dc '[:alpha:]' |head -c8`touch $i${rd_char}.htmldonels -l /data/testdir#执行[root@centos8 script]#bash for_10html.sh总用量 0-rw-r--r--. 1 root admins 0 6月 23 22:34 10eVIzhrBe.html-rw-r--r--. 1 root admins 0 6月 23 22:34 1VHeejVDO.html-rw-r--r--. 1 root admins 0 6月 23 22:34 2Nvrplexr.html-rw-r--r--. 1 root admins 0 6月 23 22:34 3rRCcVydS.html-rw-r--r--. 1 root admins 0 6月 23 22:34 4GjWKiKMC.html-rw-r--r--. 1 root admins 0 6月 23 22:34 5ljzcoBDr.html-rw-r--r--. 1 root admins 0 6月 23 22:34 6DiokAZGm.html-rw-r--r--. 1 root admins 0 6月 23 22:34 7BqpdiTTA.html-rw-r--r--. 1 root admins 0 6月 23 22:34 8lAqICtaT.html-rw-r--r--. 1 root admins 0 6月 23 22:34 9fOyYIrqP.html

9.打印等腰三角形

解析:关键是找出两个变量关系:1)空格符和行数line、第几行 i 的关系,2)*号和第几行 i 的关系

[root@centos8 script]#cat for_tri.sh#!/bin/bashread -p "请输入三角形的行数:" linefor((i=1;i<=line;i++));dofor((j=line-i;j>0;j--));doecho -e " \c"donefor((k=1;k<=2*i-1;k++));doecho -e "*\c"doneechodone[root@centos8 script]#bash for_tri.sh 请输入三角形的行数:3*********[root@centos8 script]#bash for_tri.sh 请输入三角形的行数:9*********************************************************************************

10.猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半加一个。到第10天早上想再吃时,只剩下一个桃子了。求第一天共摘了多少?

解析:和第9题相似,先找变量之间的关系。采用逆向思维,第 i 天剩余桃子的数量是n,那么前一天剩余桃子的数量是 (n+1)*2;并且在第10天想再吃时只有1个桃子了,也就是说第9天吃完后剩余桃子的数量是1个

[root@centos8 script]#cat for_monkey_peach.sh#!/bin/bashn=1echo -e "第9天\t剩余桃子数量:$n"for ((i=8;i>=1;i--));dolet n=2*n+2echo -e "第$i天\t剩余桃子数量:$n"done#求出第一天还没吃之前桃子的数量,即桃子的总数量,所以还需要在算一次n=$[2*n+2]echo "猴子第一天摘了$n个桃子"[root@centos8 script]#bash for_monkey_peach.sh第9天剩余桃子数量:1第8天剩余桃子数量:4第7天剩余桃子数量:10第6天剩余桃子数量:22第5天剩余桃子数量:46第4天剩余桃子数量:94第3天剩余桃子数量:190第2天剩余桃子数量:382第1天剩余桃子数量:766猴子第一天共摘了1534个桃子#知道桃子总数量结果后计算每天桃子剩余数量n=1534for((i=1;i<=9;i++));dolet n=n/2-1echo -e "第$i天\t剩余桃子数量是:$n"done[root@centos8 script]#bash for_monkey_peach2.sh第1天剩余桃子数量是:766第2天剩余桃子数量是:382第3天剩余桃子数量是:190第4天剩余桃子数量是:94第5天剩余桃子数量是:46第6天剩余桃子数量是:22第7天剩余桃子数量是:10第8天剩余桃子数量是:4第9天剩余桃子数量是:1

11.鸡兔同笼算法,今有雉兔同笼,上有三十五头,下有九十四足,问雉兔各几何?

[root@centos8 script]#cat chick_rabbit.sh#!/bin/bash#头和脚的数量已知,取输入的$1,$2#假设头的数量是a,脚的数量是b;鸡的数量是x,兔子的数量是y#x+y=a,2x+4y=b(x+2y=b/2);用a,b的算式代表x,y,如下:#y=(b-2a)/2,x=a-yHEAD=$1FOOT=$2RABBIT=$(((FOOT-2*HEAD)/2))CHICK=$((HEAD-RABBIT))echo chicken:$CHICKecho rabbit:$RABBIT[root@centos8 script]#bash chick_rabbit.sh 35 94chicken:23rabbit:12

12.选择输入yes or no

[root@centos8 script]#cat yesorno_case_tr.sh #!/bin/bashread -p "Are you OK (Yes/No) ?" answeranswer=`echo $answer |tr "A-Z" "a-z"`#使用tr统一转换成小写字母case $answer iny|yes)echo "Yes";;n|no)echo "No";;*)echo "You input is error";;esac[root@centos8 script]#sh yesorno_case_tr.shAre you OK (Yes/No) ?YeSYes[root@centos8 script]#sh yesorno_case_tr.shAre you OK (Yes/No) ?nONo

for循环总结

1. 随机字符的生成

cat /dev/urandom |tr -dc '[:alnum:]' |head -c8cat /dev/urandom |tr -dc '[:alpha:]' |head -c8cat /dev/urandom |tr -dc '0-9' |head -c8

tr 这个命令真的是太厉害了

2. 在for循环中的数值运算

for i in {1..10} #从1到10,默认增量是1for i in {1..100..3} #从1到100,增量是3for i in {1..$j} #错误写法,在{}里不可调用变量,正确的使用方法是for i in `seq $j`#for的双括号表示方法for ((sum=0,i=1;i<=100;sum+=i,i++));do ture;done#seq 的几种使用方法[root@centos8 script]#echo `seq 10`#1到10,默认增量是11 2 3 4 5 6 7 8 9 10[root@centos8 script]#echo `seq 5 10` #5到10,默认增量是15 6 7 8 9 10[root@centos8 script]#echo `seq 10 2 20` #seq [首数] [增量] [尾数]10 12 14 16 18 20

3. 像鸡兔同笼,九九乘法表,等腰三角形,猴子吃桃这类题,重点是发现规律并列出变量表达式。在猴子吃桃例子中,表达式n=2*n+2和递增变量 i 并无直接关系,只是表达式执行 i 次而已。

六. while循环

1、编写脚本,求100以内所有正奇数之和

#!/bin/bash#1除于2的余数是1sum=0i=1while [ $i -le 100 ];do[ `echo $i%2 |bc` == 1 ] && let sum+=ilet i++doneecho $sum

2、编写脚本,提示请输入网络地址,如192.168.0.0,判断输入的网段中主机在线状态,并统计在线和离线主机各多少

#!/bin/bashread -p "请输入要测试的网络地址,例如:192.168.0.0。network:" networkNET=`echo $network |sed 's/\.0$//g'`i=0;j=0n=200while [ $n -le 254 ];doip=$NET.$nping -c1 -W1 $ip > /dev/null && {i=$[i+1];echo $ip is up; } || {j=$[j+1];echo $ip is down; }let n++doneecho -e " $i hosts on-line\n $j hosts off-line"[root@centos8 while]#bash while_ping.sh请输入要测试的网络地址,例如:192.168.0.0。network:192.168.13.0192.168.13.60 is down192.168.13.61 is down192.168.13.62 is down192.168.13.63 is down......192.168.0.248 is up192.168.0.249 is up192.168.0.250 is down192.168.0.251 is down192.168.0.252 is down192.168.0.253 is down192.168.0.254 is up11 hosts on-line44 hosts off-line

3、编写脚本,打印九九乘法表

[root@centos8 while]#vim whinle_9x9.sh#!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-14#FileName: whinle_9x9.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************i=1while [ $i -le 9 ];doj=1while [ $j -le $i ];dolet k=$j*$iecho -e "${j}x$i=$k\t\c"let j++doneecholet i++;done[root@centos8 while]#bash whinle_9x9.sh1x1=11x2=22x2=41x3=32x3=63x3=91x4=42x4=83x4=124x4=161x5=52x5=103x5=154x5=205x5=251x6=62x6=123x6=184x6=245x6=306x6=361x7=72x7=143x7=214x7=285x7=356x7=427x7=491x8=82x8=163x8=244x8=325x8=406x8=487x8=568x8=641x9=92x9=183x9=274x9=365x9=456x9=547x9=638x9=729x9=81

4、编写脚本,利用变量RANDOM生成10个随机数字,输出这个10数字,并显示其中的最大值和最小值

[root@centos8 while]#vim while_rdm_num.sh#!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-13#FileName: while_rdm_num.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************n=1while [ $n -le 10 ];donum=$RANDOMecho 第$n个数:$num[ $n -eq 1 ] && {max=$num;min=$num; } || {[ $num -gt $max ] && max=$num[ $num -lt $min ] && min=$num ; }let n++doneecho 最大的数是:$max,最小的数是:$min[root@centos8 while]#bash while_rdm_num.sh第1个数:17757第2个数:17605第3个数:25277第4个数:7062第5个数:9038第6个数:16542第7个数:12370第8个数:28615第9个数:18860第10个数:29296最大的数是:29296,最小的数是:7062

5、编写脚本,实现打印国际象棋棋盘

[root@centos8 while]#vim while_chess.sh#!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-14#FileName: while_chess.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************i=2while [ $i -le 9 ];doj=1while [ $j -le 4 ];do[ $[i%2] -eq 0 ] && echo -e "\e[1;45m \e[0m\e[1;47m \e[0m\c" || echo -e "\e[1;47m \e[0m\e[1;45m \e[0m\c"let j++doneecholet i++done

执行结果:

6、破解这些字符串对应的RANDOM值

后续六个字符串:efbaf275cd、4be9c40b8b、44b2395c46、f8c8873ce0、b902c16c8b、ad865d2f63是通过对随机数变量RANDOM随机执行命令: echo $RANDOM|md5sum|cut -c1-10后的结果,请破解这些字符串对应的RANDOM值

单个字符串破解[root@centos8 while]#vim until_crack_string.sh#!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-14#FileName: vim until_crack_string.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************char1=4be9c40b8brdm=$RANDOMrdmchar=`echo $rdm|md5sum|cut -c1-10`until [ "$rdmchar" = "$char1" ]; dordm=$RANDOMrdmchar=`echo $rdm|md5sum|cut -c1-10`doneecho $rdm[root@centos8 while]#bash while_crack_rdm.sh12000[root@centos8 while]#cat while_crack_string1.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-14#FileName: while_crack_string1.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************i=0while [ $i -le 32767 ];dostring=`echo $i|md5sum|cut -c1-10`case $string inefbaf275cd)echo efbaf275cd:$i;;4be9c40b8b)echo 4be9c40b8b:$i;;44b2395c46)echo 44b2395c46:$i;;f8c8873ce0)echo f8c8873ce0:$i;;b902c16c8b)echo b902c16c8b:$i;;ad865d2f63)echo ad865d2f63:$iesaclet i++done[root@centos8 while]#bash while_crack_string1.shad865d2f63:1000b902c16c8b:3000f8c8873ce0:600044b2395c46:90004be9c40b8b:12000efbaf275cd:15000

七. 循环控制continue,break,shift

1、每隔3秒钟到系统上获取已经登录的用户的信息;如果发现用户hacker登录,则将登录时间和主机记录于日志/var/log/login.log中,并退出脚本

[root@centos8 contbreak]#cat break_hacker.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-19#FileName: break_hacker.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#*******************************************************************while :;doif `who |grep liudh 1>/var/log/login.log`;thenbreakfidone

2、随机生成10以内的数字,实现猜字游戏,提示比较大或小,相等则退出

[root@centos8 contbreak]#cat break_guessdigit.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-19#FileName: guessdigit.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************NUM=$[RANDOM%10]while read -p "请输入0-9之间的数字:" INPUT ;doif [ $INPUT -gt 9 ];thenecho "输入有误,必须是0-9之间的数字"breakelif [ $NUM -eq $INPUT ];thenecho "恭喜你猜对了"breakelif [ $NUM -gt $INPUT ];thenecho "太小了,请重猜"elseecho "太大了,请重猜"fidone

3、用文件名做为参数,统计所有参数文件的总行数

[root@centos8 while]#cat while_read_file.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-20#FileName: while_read_file.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************total=0path=/root/scriptls $path | {while read filename;doif [ -f $path/$filename ];thenlines=`cat $path/$filename|wc -l`total=$[$total+$lines]fidoneecho $total}#管道符会开启子进程,while循环是子进程,而total是在while内,while结束后total的值就会消失。#为了引用while内的值,可以把while和echo用{}括起来,表示把echo放到while所在的子进程

4、用二个以上的数字为参数,显示其中的最大值和最小值

[root@centos8 shift]#cat shift.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-20#FileName: shift.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************[ -z $1 ] || [ -z $2 ] && {echo -e "输入有误,重新输入,如:$0 num1 num2" ;exit; }#参数两个以上检查for num in $* ;do[[ "$num" =~ ^[0-9]+$ ]] || {echo "输入的参数必须是纯数字"; exit; }done#所有参数必须为数字max=$1;min=$1while [ -n "$2" ];do[ $2 -gt $max ] && max=$2[ $2 -lt $min ] && min=$2shiftdoneecho -e "Maxnumber is $max\nMinnumber is $min"[root@centos8 shift]#bash shift.sh输入有误,重新输入,如:shift.sh num1 num2[root@centos8 shift]#bash shift.sh 8输入有误,重新输入,如:shift.sh num1 num2[root@centos8 shift]#bash shift.sh 8 a 9输入的参数必须是纯数字[root@centos8 shift]#bash shift.sh 99 999 105 1000 3Maxnumber is 1000Minnumber is 3

八. 函数

1.编写函数,实现OS的版本判断

[root@centos8 function]#cat func_os.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-20#FileName: func_os.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************OS() {if cat /etc/redhat-release &> /dev/null;thenOS_NAME=CentOSOS_ID=`sed -nr 's/.*release ([0-9]+)\..*/\1/p' /etc/redhat-release`OS="${OS_NAME} ${OS_ID}"elseOS=Ubantufi}OSecho $OS[root@centos8 function]#bash func_os.sh CentOS 8[root@centos7 ~]#bash func_os.sh CentOS 7[root@Centos6 ~]#bash func_os.sh CentOS 6[root@ubuntu1804 ~]#bash func_os.sh Ubantu

2. 编写函数,实现取出当前系统eth0的IP地址

[root@centos8 function]#cat func_eth0_IP.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-20#FileName: func_eth0_IP.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************OS() {if cat /etc/redhat-release &> /dev/null;thenOS_NAME=CentOSOS_ID=`sed -nr 's/.*release ([0-9]+)\..*/\1/p' /etc/redhat-release`OS="${OS_NAME} ${OS_ID}"elseOS=Ubantufi}GET_IP() {if [ "${OS}" = "CentOS 6" ];thenIP=`ifconfig eth0 |sed -nr '/^.*inet /s/.*addr:(.*) B.*/\1/p'`elseIP=`ifconfig eth0 |sed -nr '/^.*net /s#^.*net (.*) net.*#\1#p'`fi}OSGET_IPecho -e "OS:${OS}\nIP:$IP"3个系统的执行结果[root@ubuntu1804 ~]#bash func_eth0_IP.sh OS:UbantuIP:10.0.0.151[root@Centos6 ~]#bash func_eth0_IP.sh OS:CentOS 6IP:10.0.0.153[root@centos7 ~]#bash func_eth0_IP.sh OS:CentOS 7IP:10.0.0.152[root@centos8 function]#bash func_eth0_IP.sh OS:CentOS 8IP:10.0.0.154

3. 编写函数,实现打印绿色OK和红色FAILED

用的是王老师代码[root@centos8 function]#vim ok_failed.shcolor () {RES_COL=60MOVE_TO_COL="echo -en \\033[${RES_COL}G"SETCOLOR_SUCCESS="echo -en \\033[1;32m"SETCOLOR_FAILURE="echo -en \\033[1;31m"SETCOLOR_WARNING="echo -en \\033[1;33m"SETCOLOR_NORMAL="echo -en \E[0m"echo -n "$1" && $MOVE_TO_COLecho -n "["if [ $2 = "success" -o $2 = "0" ] ;then${SETCOLOR_SUCCESS}echo -n $" OK " elif [ $2 = "failure" -o $2 = "1" ] ;then${SETCOLOR_FAILURE}echo -n $"FAILED"else${SETCOLOR_WARNING}echo -n $"WARNING"fi${SETCOLOR_NORMAL}echo -n "]"echo }color success! 0color failed! 1[root@centos8 function]#bash ok_failed.shsuccess! [ OK ]failed! [FAILED]调用系统函数库

4. 编写函数,实现判断是否无位置参数,如无参数,提示错误

[root@centos8 function]#cat func4_parameter.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-23#FileName: func4_parameter.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************. /etc/init.d/functionsparameter () {[ -z "$1" ] && action "No parameter,Input many parameter" false}parameter $1

5. 编写函数,实现两个数字做为参数,返回最大值

[root@centos8 function]#cat func5_max.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-23#FileName: func5_max.sh#URL: #Description:The test script#Copyright (C): All rights reserved#*******************************************************************i*get_max() {[ $1 -ge $2 ] && max=$1 || max=$2echo "最大值是:$max"}get_max $1 $2

6. 编写服务脚本/root/bin/testsrv.sh,完成如下要求

(1) 脚本可接受参数:start, stop, restart, status

(2) 如果参数非此四者之一,提示使用格式后报错退出

(3) 如是start:则创建/var/lock/subsys/SCRIPT_NAME, 并显示“启动成功”

考虑:如果事先已经启动过一次,该如何处理?

(4) 如是stop:则删除/var/lock/subsys/SCRIPT_NAME, 并显示“停止完成”

考虑:如果事先已然停止过了,该如何处理?

(5) 如是restart,则先stop, 再start

考虑:如果本来没有start,如何处理?

(6) 如是status, 则如果/var/lock/subsys/SCRIPT_NAME文件存在,则显示“SCRIPT_NAME is

running…”,如果/var/lock/subsys/SCRIPT_NAME文件不存在,则显示“SCRIPT_NAME is

stopped…”

(7)在所有模式下禁止启动该服务,可用chkconfig 和 service命令管理

说明:SCRIPT_NAME为当前脚本名

7. 编写脚本/root/bin/copycmd.sh

(1) 提示用户输入一个可执行命令名称

(2) 获取此命令所依赖到的所有库文件列表

(3) 复制命令至某目标目录(例如/mnt/sysroot)下的对应路径下

如:/bin/bash ==> /mnt/sysroot/bin/bash

/usr/bin/passwd ==> /mnt/sysroot/usr/bin/passwd

(4) 复制此命令依赖到的所有库文件至目标目录下的对应路径下: 如:/lib64/ld-linux-x86-

64.so.2 ==> /mnt/sysroot/lib64/ld-linux-x86-64.so.2

(5)每次复制完成一个命令后,不要退出,而是提示用户键入新的要复制的命令,并重复完成上述

功能;直到用户输入quit退出

8. 斐波那契数列又称黄金分割数列,因数学家列昂纳多·斐波那契以兔子繁殖为例子而引入,故又称

为“兔子数列”,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……,斐波纳契数列

以如下被以递归的方法定义:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2),利用函数,

求n阶斐波那契数列

[root@centos8 function]#cat feibonaci.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-23#FileName: feibonaci.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************feibonaci() {if [ $1 == 0 ];thenecho 0elif [ $1 == 1 ];thenecho 1elseFa=`feibonaci $[$1-1]`Fb=`feibonaci $[$1-2]`echo $[Fa+Fb]fi}feibonaci $1[root@centos8 function]#bash feibonaci.sh 934[root@centos8 function]#bash feibonaci.sh 1055[root@centos8 function]#bash feibonaci.sh 1189[root@centos8 function]#bash feibonaci.sh 182584

9. 汉诺塔(又称河内塔)

汉诺塔(又称河内塔)问题是源于印度一个古老传说。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘,利用函数,实现N片盘的汉诺塔的移动步骤

九. 数组

1. 输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序

代码1:不是冒泡法,称它为剔除法

#!/bin/bash# #********************************************************************#Author:LingXia#QQ:1589640561#Date: -08-03#FileName: array_maopao.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************rd_num(){local kfor ((k=0;k<10;k++));donums[$k]=$RANDOMdone}rd_num#read -p "输入若干个正整数:" -a numsdeclare -a sortsecho "all numbers:${nums[@]}"index=$[${#nums[@]}-1]for j in `seq 0 $[$index-1]`;do #减少一次循环max=0for i in `seq $index -1 0` ;do[ ${nums[$i]} -gt $max ] 2> /dev/null && max=${nums[$i]} && un=$idonesorts[$j]=$maxunset nums[$un]donesorts[$index]=${nums[*]} #最后一次循环没有执行,但此时nums数组中只剩一个最小的数,直接赋值echo sort nums:${sorts[*]}[root@centos8 array]#bash array_maopaov2.shall numbers:31561 10857 3473 23516 22383 28170 28943 7555 7979 18121sort nums:31561 28943 28170 23516 22383 18121 10857 7979 7555 3473

代码2:冒泡法经典写法

[root@centos8 array]#cat array_mpv3.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -08-04#FileName: array_mpv3.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************#产生随机数存入数组中RD_NUMS(){local kfor ((k=0;k<10;k++));donums[$k]=$RANDOMdone}#相邻数据交换SWITCH(){tmp=${nums[$j]};nums[$j]=${nums[$j+1]};nums[$j+1]=$tmp}ARRAY_SORT(){#数组随机生成或者手动输入RD_NUMS#read -p "输入若干个正整数:" -a numsecho before ${nums[*]}length=${#nums[*]}for ((i=1;i<$length;i++));dofor ((j=0;j<$length-$i;j++));do[ ${nums[$j]} -gt ${nums[$j+1]} ] && SWITCHdonedoneecho after ${nums[*]}}ARRAY_SORT[root@centos8 array]#bash array_mpv3.sh before 17344 11123 5727 26543 15678 17508 3502 16597 3877 25841after 3502 3877 5727 11123 15678 16597 17344 17508 25841 26543

当排序600个数时,两个代码耗费的时间[root@centos8 array]#time (bash array_maopaov2.sh)real0m6.990suser0m4.658ssys 0m2.185s[root@centos8 array]#time (bash array_mpv3.sh)real0m2.755suser0m2.735ssys 0m0.000s经典写法优于剔除法

2. 将下图所示,实现转置矩阵 matrix.sh

1 2 31 4 74 5 6 ===> 2 5 87 8 93 6 9

分析:给这些数字放到一个关联数组中,下标用 i j 两个数字的组合来命名。观察发现当 i=i=i=j 时不用交换,为避免重复交换,在遍历数组时,发现只要当i<j 时交换即可

[root@centos8 array]#cat array_matrix.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -08-04#FileName: array_matrix.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************cr_array(){#a=1for ((i=1;i<=3;i++));dofor ((j=1;j<=3;j++));donums[$i$j]=$[3*$[i-1]+j] #nums[$i$j]=$a#let a++echo -e "${nums[$i$j]} \c"doneechodone}switch(){temp=${nums[$i$j]};nums[$i$j]=${nums[$j$i]};nums[$j$i]=$temp}tr_array(){for ((i=1;i<=3;i++));do #当i=2时,九宫格内即可完成所有数值的调换,但需要执行调换后的输出信息,所以还是需要执行i=3的循环。for ((j=1;j<=3;j++));do[ $i -lt $j ] && switchecho -e "${nums[$i$j]} \c"doneechodone}declare -A numsecho before:cr_arrayecho after:tr_array[root@centos8 array]#bash array_matrix.sh before:1 2 3 4 5 6 7 8 9 after:1 4 7 2 5 8 3 6 9#想要转换n*n的方针也可以用此代码,把3换成n即可实现

3. 打印杨辉三角形

代码1:网上普遍流行的写法

[root@centos8 array]#vim array_yanghui.sh #!/bin/bashread -p "请输入行数:" n#i表示当前行#j表示当前位置#f表示上一行#g表示前一个位置#declare 变量声明for ((i=1;i<=$n;i++));dofor ((j=1;j<=i;j++));dof=$[i-1];g=$[j-1]if [ $j -eq $i ] || [ $j -eq 1 ];thendeclare SUM_${i}_$j=1elsedeclare A=$[SUM_${f}_$j] #取上一行的j位置变量declare B=$[SUM_${f}_$g] #取上一行的j-1位置变量declare SUM_${i}_$j=$[A+B]fiecho -en $[SUM_${i}_$j]" " #输出当前变量,不换行doneecho #换行done[root@centos8 array]#bash array_yanghui.sh 请输入行数:101 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1

代码2:

逻辑和代码1一样,只是利用变量动态生成数组,每行一个数组

eval 先置换变量再执行命令,相当于两次执行,第一次先转译变量,第二次实际执行

[root@centos8 array]#cat array_yanghuiv3.sh#!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -08-05#FileName: array_yanghuiv3.sh#URL: /weixin_41142408#Description:The test script#Copyright (C): All rights reserved#********************************************************************#数组名动态生成,并引用数组的值#exp:for((i=4;i<=8;i++));do eval a$i[0]=$i;eval aa=\${a$i[0]};echo $aa;done#eval 先置换变量再执行命令,相当于两次执行,第一次先转译变量,第二次实际执行read -p "请输入要显示多少行:" nfor ((i=1;i<=$n;i++));dodeclare -a eval line$i #每行一个数组for ((j=0;j<$i;j++));doa=$[i-1];b=$[j-1] #a是上一行,b是前一个变量if [ $j -eq 0 -o $j -eq $[i-1] ];theneval line$i[$j]=1elseeval A=\${line$a[$j]} #eval置换时${}不能被置换,先用\转义掉eval B=\${line$a[$b]}eval line$i[$j]=$[A+B]fidoneeval echo \${line$i[*]} #行结束后输出数组的所有元素done[root@centos8 array]#bash array_yanghuiv3.sh请输入要显示多少行:1011 11 2 11 3 3 11 4 6 4 11 5 10 10 5 11 6 15 20 15 6 11 7 21 35 35 21 7 11 8 28 56 70 56 28 8 11 9 36 84 126 126 84 36 9 1

十.expect的应用

以scp命令为例

该脚本主要用于学习时各版本主机间复制文件用,所有主机root密码相同

[root@centos8 script]#cat scp_expectv2.sh #!/bin/bash##********************************************************************#Author:LingXia#QQ:1589640561#Date: -07-22#FileName: scp.sh#URL: #Description:The test script#Copyright (C): All rights reserved#********************************************************************rpm -q expect &> /dev/null || yum -y install expect > /dev/nullecho "本脚本主要用于C8向其他主机发送测试文件"echo -e "\e[1;$[$RANDOM%7+31]m"PS3="请选择将文件复制到哪 (1-6):"select os in Centos8_154 Centos7_152 Centos6_153 Ubantu_151 C7+C6+U 选择完成,开始复制;docase $REPLY in1)ip="10.0.0.154";;2)ip="10.0.0.152";;3)ip="10.0.0.153";;4)ip="10.0.0.151";;5)ip1="10.0.0.152"ip2="10.0.0.153"ip3="10.0.0.151";;6)echo "选择完成,开始复制"break;;*)echo "选择有误,请重新选择" exit;;esacdoneecho -e "\e[0m"user=rootpasswd="xxxxxx" #所有主机密码相同for id in $ip $ip1 $ip2 $ip3;doexpect <<EOFset timeout 20spawn scp $1 $user@$id:/root/expect {"yes/no" { send "yes\n"; exp_continue }"password" { send "$passwd\n" }}expect eofEOFdone

如果觉得《shell脚本练习-课后练习》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。