AI智能
改变未来

作业–SHELL脚本编程练习答案(多版本)

练习:
1、编写脚本 systeminfo.sh,显示当前主机系统信息,包括:主机名,IPv4地址,操作系统版本,内核
版本,CPU型号,内存大小,硬盘大小

#!/bin/bashYELLOW=\'\\e[1;33m\'RED=\'\\e[1;31m\'END=\'\\e[0m\'echo -e \"${YELLOW}++++++++++++++++++++++++++++++++++++++++++${END}\"echo -e \"${RED}HOSTNAME:        `hostname`${END}\"echo -e \"${RED}IPADDR:          `hostname -I`${END}\"echo -e \"${RED}OS\'s version:    `cat /etc/centos-release`${END}\"echo -e \"${RED}Kernel version:  `uname -r`${END}\"echo -e \"${RED}CPU:            `lscpu |egrep \'^Model name\'|tr -s \' \'|cut -d: -f2`${END}\"echo -e \"${RED}Memory size:     `free -h|sed -rn \'2p\'|tr -s \' \'|cut -d\' \' -f2`${END}\"echo -e \"${RED}Disk size:       `lsblk |sed -n \'2p\'|egrep -o \'([0-9]+)G\'`${END}\"echo -e \"${YELLOW}++++++++++++++++++++++++++++++++++++++++++${END}\"

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

#!/bin/bashRED=\'\\e[1;31m\'GREEN=\'\\e[1;32m\'END=\'\\e[0m\'SOURCE=\"/etc\"DEST=\"/backup\"[ ! -d $DEST ] && { mkdir $DEST;echo -e \"${RED}Start backup...${END}\";sleep 3;cp -av $SOURCE $DEST/etc`date +%F`;echo -e \"${GREEN}Back is finished.${END}\"; } || { echo -e \"${RED}Start backup...${END}\";sleep 3;cp -av $SOURCE $DEST/etc`date +%F`;echo -e \"${GREEN}Back is finished.${END}\"; }

版本2:

#!/bin/bashRED=\'\\e[1;31m\'GREEN=\'\\e[1;32m\'END=\'\\e[0m\'SOURCE=\"/etc\"DEST=\"/backup\"if [ ! -d $DEST ];thenmkdir $DESTecho -e \"${RED}Start backup...${END}\"sleep 3cp -av $SOURCE $DEST/etc`date +%F`echo -e \"${GREEN}Back is finished.${END}\"elseecho -e \"${RED}Start backup...${END}\"sleep 3cp -av $SOURCE $DEST/etc`date +%F`echo -e \"${GREEN}Back is finished.${END}\"fi

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

#!/bin/bashCOLOR=\'\\e[1;36m\'END=\'\\e[0m\'MAX=`df|egrep \'^/dev/sd\'|egrep -o \'([0-9]+)%\' |tr -d \'%\'|sort -nr|head -1`echo -e \"${COLOR}The maximum value of space is $MAX in the hard disk partition.${END}\"

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

#!/bin/bashCOLOR=\'\\e[1;34m\'END=\'\\e[0m\'RESULT=`netstat -tan|egrep \'ESTABLISHED\'|tr -s \' \' :|cut -d: -f6|sort|uniq -c|sort -nr`echo -e \"${COLOR}Active Internet connections\'s status:\\n${RESULT}${END}\"

1、编写脚本 argsnum.sh,接受一个文件路径作为参数;如果参数个数小于1,则提示用户“至少应该给
一个参数”,并立即退出;如果参数个数不小于1,则显示第一个参数所指向的文件中的空白行数
版本1:

#!/bin/bash[ $# -lt 1 ] && { echo -e \"\\e[1;31mPlease at least give an argument.\\e[0m\";exit 2; }[ $# -ge 1 ] && echo -e \"\\e[1;35mBlank lines is `grep \'^$\' $1 $2 $3|wc -l`.\\e[0m\"

版本2:

#!/bin/bashif [ $# -lt 1 ];thenecho -e \"\\e[1;31mPlease at least input a filename as an argument.\\e[0m\"exit 2elseecho -e \"\\e[1;36mBlank line is `egrep \'^$\' $1 $2 $3 | wc -l`.\\e[0m\"fi

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

#!/bin/bashIP=10.0.0.7RED=\'\\e[1;31m\'GREEN=\'\\e[1;32m\'ping -c1 -W1 $IP &> /dev/null && echo -e \"${GREEN}${IP} is up.${END}\" || echo -e \"${RED}${IP} is down.${END}\"

版本2:

#!/bin/bashRED=\'\\e[1;31m\'GREEN=\'\\e[1;32m\'END=\'\\e[0m\'IP=10.0.0.2if ping -c1 -W1 $IP &> /dev/null;thenecho -e \"${GREEN}${IP} is up.${END}\"elseecho -e \"${RED}${IP} is down.${END}\"fi

版本3:

#!/bin/bashIP=10.0.0RED=\'\\e[1;31m\'GREEN=\'\\e[1;32m\'END=\'\\e[0m\'for i in `seq 254`;doping -c1 -W1 ${IP}.${i} &> /dev/null && echo -e \"${GREEN}${IP}.${i} is up.${END}\" || echo -e \"${RED}${IP}.${i} is down.${END}\"done

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

版本1:

#!/bin/bashWARN=20GREEN=\'\\e[1;32m\'END=\'\\e[0m\'SPACE_USED=`df|egrep \'^/dev/sd\'|egrep -o \'([0-9]+)%\' |tr -d \'%\'|sort -nr|head -1`INODE_USED=`df -i|egrep \'^/dev/sd\'|egrep -o \'([0-9]+)%\' |tr -d \'%\'|sort -nr|head -1`[ $SPACE_USED -ge $WARN -o $INODE_USED -ge $WARN ] && echo \"space will be full.\" | mail -s diskwarning 123456789@qq.com || echo -e \"${GREEN}Disk space is enough.${END}\"

版本2:

#!/bin/bashWARN=20YELLOW=\'\\e[1;33m\'END=\'\\e[0m\'DISK_USED=`df|egrep \'/dev/sd\'|egrep -o \'([0-9]+)%\'|tr -d \'%\'|sort -nr|head -1`INODE_USED=`df -i|egrep \'^/dev/sd\'|egrep -o \'([0-9]+)%\' |tr -d \'%\'|sort -nr|head -1`if [ $DISK_USED -ge $WARN -o $INODE_USED -ge $WARN ];thenecho \"Disk space will be full.\" |mail -s Diskwarning 123456789@qq.comelseecho -e \"${YELLOW}Disk space is enough.${END}\"fi

版本3:

#!/bin/bashWARN=10RED=\'\\e[1;31m\'BLUE=\'\\e[1;34m\'END=\'\\e[0m\'DISK_USED=`df|egrep \'^/dev/sd\'|egrep -o \'([0-9]+)%\' |tr -d \'%\'`for i in $DISK_USED;do[ $i -ge $WARN ] && echo -e \"${RED}Disk space will be full.${END}\" || echo -e \"${BLUE}Disk space is enough.${END}\"done

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

#!/bin/bashread -p \"Please input a filename: \" FILE[ ! -r $FILE -a ! -w $FILE ] && echo \"$FILE is not readable and not writeable\" || echo \"$FILE is readable or writeable.\"

版本2:

#!/bin/bashCOLOR1=\'\\e[1;33m\'COLOR2=\'\\e[1;34m\'END=\'\\e[0m\'if [ $# -ne 0 ];then[ ! -r $1 -a ! -w $1 ] && echo -e \"${COLOR1}$1 is not readable and not writeable.${END}\" || echo -e \"${COLOR2}$1 is readable or writeable.${END}\"elseecho -e \"${COLOR1}Please input a file.${END}\"fi

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

#!/bin/bashRED=\'\\e[1;31m\'YELLOW=\'\\e[1;33m\'END=\'\\e[0m\'read -p \"Please input a filename: \" FILE[[ \"$FILE\" =~ ^.*\\.sh$ ]] && { chmod a+x $FILE;echo -e \"${YELLOW}${FILE}\'s executeable is added.${END}\"; }  || echo -e \"${RED}${FILE} is not a script file.${END}\"

版本2:

#!/bin/bashRED=\'\\e[1;31m\'YELLOW=\'\\e[1;33m\'END=\'\\e[0m\'read -p \"Please input a filename: \" FILEif [[ \"$FILE\" =~ ^.*\\.sh$ ]];thenchmod a+x $FILEecho -e \"${YELLOW}${FILE}\'s executeable permission is added.${END}\"elseecho -e \"${RED}${FILE} is not a script file.${END}\"fi

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

#!/bin/bashYELLOW=\'\\e[1;33m\'END=\'\\e[0m\'FILE=\"/etc/nologin\"[ ! -e $FILE ] && { touch $FILE; echo -e \"${YELLOW}Prohibit common user login.${END}\"; } || echo -e \"${YELLOW}Cmmon user can not login.${END}\"

版本2:

#!/bin/bashYELLOW=\'\\e[1;33m\'RED=\'\\e[1;31m\'END=\'\\e[0m\'FILE=\"/etc/nologin\"if [ ! -e $FILE ];thentouch $FILEecho -e \"${YELLOW}Prohibit common user login.${END}\"elseecho -e \"${RED}Cmmon user can not login.${END}\"fi

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

echo \"export PATH=/usr/local/apache/bin:$PATH\" >> /etc/profilesource /etc/profileecho $PATH

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)

echo PS1=\"\\[\\e[1;32m\\][\\[\\e[0m\\]\\[\\e[1;32m\\]\\u\\[\\e[32m\\]@\\h\\[\\e[1;32m\\] \\W\\[\\e[1;32m\\]]\\[\\e[0m\\]\\\\$ \" >> /etc/profile.d/env.shcat <<EOF >> ~/.bashrc>rm=\'rm -i\'>cdnet=\'cd /etc/sysconfig/network-scripts/\'>editnet=\'vim /etc/sysconfig/network-scripts/ifcfg-eth0\'>EOF

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

echo -e \"\\e[1;31mHi,dangerous!\\e[0m\" >> /etc/motd

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

vim ~/.vimrcset ts=2set expandtabset ignorecaseset autoindentautocmd BufNewFile *.sh exec \":.call SetTitle()\"func SetTitle()if expand(\"%:e\") == \'sh\'call setline(1,\"#!/bin/bash\")call setline(2,\"#***********************************************\")call setline(3,\"#Author:         Kingdom_xu\")call setline(4,\"#Mail:           123456789@qq.com\")call setline(5,\"#Version:        1.0\")call setline(6,\"#Date:           \".strftime(\"%Y-%m-%d\"))call setline(7,\"#FileName:       \".expand(\"%\"))call setline(8,\"#Description:    The test script\")call setline(9,\"#Copyright (C):  \".strftime(\"%Y\").\" All rights reserved\")call setline(10,\"#***********************************************\")call setline(11,\"\")endifendfuncautocmd BufNewFile * normal G

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

#!/bin/bashread -p \"Please input a username: \" NAME[ -z $NAME ] && { echo -e \"\\e[1;33mPlease give a username.\\e[0m\";exit 2; }id $NAME &> /dev/null && { echo -e \"\\e[1;36m$NAME is exist.\\e[0m\"; } || { useradd $NAME;echo $NAME:123456 | chpasswd $NAME;getent passwd $NAME;passwd -e $NAME &> /dev/null; }

版本2:

#!/bin/bashread -p \"Please input a username: \" NAMEif [ -z $NAME ];thenecho -e \"\\e[1;37mInput a username.\\e[0m\"exit 2fiif getent passwd $NAME;thenecho -e \"\\e[1;32m$NAME is exist.\\e[0m\"elseuseradd $NAMEecho $NAME:123456 | chpasswd $NAMEid $NAMEpasswd -e $NAME &> /dev/nullfi

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

#!/bin/bashread -p \"Please input yes or no: \" ANScase $ANS in[Yy]|[Yy][Ee][Ss])echo -e \"\\e[1;34mYour answer is YES.\\e[0m\";;[Nn]|[Nn][Oo])echo -e \"\\e[1;35mYour answer is NO.\\e[0m\";;*)echo -e \"\\e[1;33mPlease input yse or no.\\e[0m\"esac

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

#!/bin/bashread -p \"Input a filename: \" FILETYPE=`ls -ld $FILE|egrep -o \'^.\'`case $TYPE in-)echo -e \"\\e[1;31m$FILE is a normal file.\\e[0m\";;d)echo -e \"\\e[1;32m$FILE is a directory file.\\e[0m\";;l)echo -e \"\\e[1;33m$FILE is a link file.\\e[0m\";;b)echo -e \"\\e[1;34m$FILE is a block file.\\e[0m\";;c)echo -e \"\\e[1;35m$FILE is a character file.\\e[0m\";;s)echo -e \"\\e[1;36m$FILE is a socket file.\\e[0m\";;p)echo -e \"\\e[1;37m$FILE is a pipe file.\\e[0m\";;*)echo -e \"\\e[1;31m$FILE is other type file.\\e[0m\"esac

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

#!/bin/bashread -p \"Please input a digit: \" NUM[[ \"$NUM\" =~ ^[0-9]+$ ]] && echo -e \"\\e[1;32m$NUM is a positive integer.\\e[0m\" || echo -e \"\\e[1;31m$NUM is not a positive integer.\\e[0m\"

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

#!/bin/bashecho -e \"\\e[1;31mThis is a system initialization script.\\e[0m\"echo -e \"\\e[1;$[RANDOM%7+31]m\"cat <<EOF1)禁用SElinux、防火墙2)安装常用软件包3)更改yum源4)修改网卡名和静态地址5)别名6)vim设置7)输入错误,重新选择EOFecho -e \"\\e[0m\"read -p \"Please choose a option from menu(1-6): \" MENUcase $MENU in1)echo -e \"\\e[1;31mStarting turn off SElinux and Firewalld.\\e[0m\"egrep \'^SELINUX=\' /etc/selinux/config |sed -i \'s/enforcing/disabled/\' &> /dev/nullsetenforce 0 &> /dev/nullsystemctl stop firewall &> /dev/nullsystemctl disable --now firewall &> /dev/nullecho -e \"\\e[1;31mTurned off SElinux and firewalld finished.\\e[0m\";;2)echo -e \"\\e[1;32mStarting install many packages.\\e[0m\"yum -y install wget vim net-toolsyum -y install psmisc tree bcecho -e \"\\e[1;32mInstall packages finished.\\e[0m\";;3)echo -e \"\\e[1;33mStarting update yum resource.\\e[0m\"wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-8.repio &> /dev/nullyum makecache &> /dev/nullecho -e \"\\e[1;33mUpdate yum resource finished.\\e[0m\";;4)DIR=\"/etc/sysconfig/network-scripts\"echo -e \"\\e[1;34mStarting modify network configure.\\e[0m\"nmcli connection add type ethernet con-name eth0 ifname ens160 &> /dev/nullnmcli connection delete ens160 &> /dev/nullsed -i \'s/ens160/eth0/g\' $DIR/ifcfg-eth0  &> /dev/nullsed -i \'s/dhcp/static/\' $DIR/ifcfg-eth0 &> /dev/nullsed -i \'/^GRUB_CMDLINE_LINUX=/s/\"$/ net.ifnames=0\"/\' /etc/default/grub &> /dev/nullgrub2-mkconfig -o /boot/grub2/grub.cfg &> /dev/nullecho  \"IPADDR=10.0.0.8\\nPREFIX=24\\nGATEWAY=10.0.0.2\" >> $DIR/ifcfg-eth0echo -e \"\\e[1;34mModified network configure finished.\\e[0m\";;5)echo -e \"\\e[1;35mStarting define alias name.\\e[0m\"alias rm=\'cp -a /etc /data\'alias cdnet=\'cd /etc/sysconfig/network-scripts\'alias editnet=\'vim /etc/sysconfig/network-scripts/ifcfg-eth0\'echo -e \"\\e[1;35mDefined alias name finished.\\e[0m\";;6)echo -e \"\\e[1;36mStarting configure ~/.vimrc file.\\e[0m\"cat /data/vimrc.txt > ~/.vimrcecho -e \"\\e[1;37mConfigure ~/.vimrc finished.\\e[0m\";;*)echo -e \"\\e[1;31mInvalid option,please choose again.\\e[0m\";;esac

练习:用 for 实现
1、判断/var/目录下所有文件的类型

#!/bin/bashfor FILE in $(ls /var);doTYPE=$(ls -ld /var/$FILE|egrep -o \'^.\')case $TYPE in-)echo -e \"\\e[1;31m$FILE is normal file.\\e[0m\";;d)echo -e \"\\e[1;32m$FILE is directory file.\\e[0m\";;b)echo -e \"\\e[1;33m$FILE is block file.\\e[0m\";;c)echo -e \"\\e[1;34m$FILE is character file.\\e[0m\";;l)echo -e \"\\e[1;35m$FILE is link file.\\e[0m\";;p)echo -e \"\\e[1;36m$FILE is pipe file.\\e[0m\";;S)echo -e \"\\e[1;37m$FILE is socket file.\\e[0m\";;*)echo -e \"\\e[1;31m$FILE is other file.\\e[0m\"esacdone

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

#!/bin/bashfor i in `seq 10`;doif getent passwd user$i &> /dev/null;thenecho -e \"\\e[1;32muser$i is exist.\\e[0m\"elseuseradd user$iPASSWD=`cat /dev/urandom|tr -dc [:alnum:]|head -c8`echo user${i}:$PASSWD |chpasswd user$iecho user${i}:$PASSWD >> /data/passwd.txtecho -e \"\\e[1;35muser$i created successfully.\\e[0m\"fidone

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

#!/bin/bashFILE=`ls /etc/rc.d/rc3.d/`for i in FILE;dofind /etc/rc.d/rc3.d/S* -exec mv {} \"{} start\" \\; &> /dev/nullfind /etc/rc.d/rc3.d/K* -exec mv {} \"{} stop\" \\; &> /dev/nulldone

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

#!/bin/bash``read -p \"Please input a positive integer: \" INTfor ((i=1,sum=0;i<=$INT;i++));dolet sum+=idoneecho -e \"\\e[1;$[$RANDOM%7+31]mThe sum is $sum.\\e[0m\"

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

#!/bin/bashfor ((i=1,sum=0;i<=100;i++));doMODULO=$[i%3][ $MODULO -eq 0 ] && let sum+=idoneecho -e \"\\e[1;$[$RANDOM%7+31]mThe sum is $sum\\e[0m\"

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

#!/bin/bashIP=10.0.0RED=\'\\e[1;31m\'GREEN=\'\\e[1;32m\'END=\'\\e[0m\'for i in `seq 254`;doping -c1 -W1 ${IP}.${i} &> /dev/null && echo -e \"${GREEN}${IP}.${i} is up.${END}\" || echo -e \"${RED}${IP}.${i} is down.${END}\"done

版本2:

#!/bin/bashIP=10.0.0RED=\'\\e[1;31m\'GREEN=\'\\e[1;32m\'END=\'\\e[0m\'for ((i=1;i<=254;i++));doping -c1 -W1 ${IP}.${i} &> /dev/null && echo -e \"${GREEN}${IP}.${i} is up.${END}\" || echo -e \"${RED}${IP}.${i} is down.${END}\"done

7、打印九九乘法表
版本1:

#!/bin/bashfor i in {1..9};dofor j in `seq $i`;doecho -e \"\\e[1;$[RANDOM%7+31]m${j}x${i}=$[i*j]\\t\\c\\e[0m\"doneechodone

版本2:

#!/bin/bashfor ((i=1;i<=9;i++));dofor ((j=1;j<=i;j++));doecho -e \"\\e[1;$[RANDOM%7+31]m${j}x${i}=$[i*j]\\t\\c\\e[0m\"doneechodone

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

#!/bin/bashNAME=`cat /dev/urandom|tr -dc \'[:alpha:]\'|head -c8`DIR=/data/testdirfor i in `seq 10`;doif [ -d $DIR ];thentouch ${DIR}/${i}${NAME}.htmlelsemkdir -p $DIRtouch ${DIR}/${i}${NAME}.htmlfidone

9、打印等腰三角形

#!/bin/bashread -p \"请输入三角形的行数: \" linefor((i=1;i<=line;i++));dofor((k=0;k<=line-i;k++));doecho -e \' \\c\'donefor((j=1;j<=2*i-1;j++));doecho -e \'*\\c\'doneechodone

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

#!/bin/bashsum=1for ((n=1;n<10;n++));do  sum=$[2*$[$sum+1]]doneecho \"所摘桃子数: $sum\"``

练习:用while实现
1、编写脚本,求100以内所有正奇数之和

#!/bin/bashi=1sum=0while ((i<=100));dolet sum+=ilet i+=2doneecho -e \"\\e[1;34mThe sum is $sum.\\e[0m\"

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

#!/bin/bashIP=192.168.0i=1UP=0DOWN=0while [ $i -le 254 ] ;doif ping -c1 -W1 ${IP}.$i &> /dev/null;thenecho -e \"\\e[1;32m${IP}.${i} is up.\\e[0m\"let UP++elseecho -e \"\\e[1;31m${IP}.${i} is down.\\e[0m\"let DOWN++filet i++doneecho -e \"\\e[1;34mUP is $UP.\\e[0m\"echo -e \"\\e[1;35mDOWN is $DOWN.\\e[0m\"

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

#!/bin/bashi=1while [ $i -le 9 ];doj=1while [ $j -le $i ];doecho -e \"\\e[1;$[RANDOM%7+31]m${j}x${i}=$[i*j]\\t\\c\\e[0m\"let j++donelet i++echodone

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

i=1while true;do  NUM=$RANDOM  if [ \"$i\" -eq \"1\" ];then    MAX=$NUM    MIN=$NUM  else      if [ \"$MAX\" -lt \"${num[$i]}\" ];then      MAX=${num[$i]}    elif [ \"$MIN\" -gt \"${num[$i]}\" ];then      MIN=${num[$i]}    else      true    fi  fi  let i++doneecho \"num is : ${num[@]}\"echo \"最大值MAX:$MAX 最小值MIN:$MIN\"

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

#!/bin/bashi=1D_COLOR=\'\\033[1;41m\'S_COLOR=\'\\033[1;47m\'AND_COLOR=\'\\033[0m\'while [ $i -le 8 ];do  if [ \"$[$i%2]\" -eq \"0\" ];then    j=1    while [ $j -le 8 ];do      if [ \"$[$j%2]\" -eq \"0\" ];then        echo -e \"${S_COLOR} ${AND_COLOR}\\c\"      else        echo -e \"${D_COLOR} ${AND_COLOR}\\c\"      fi      let j++    done  else    j=1    while [ $j -le 8 ];do      if [ \"$[$j%2]\" -eq \"0\" ];then        echo -e \"${D_COLOR} ${AND_COLOR}\\c\"      else        echo -e \"${S_COLOR} ${AND_COLOR}\\c\"      fi      let j++    done  fi  echo \"\"  let i++done

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

#!/bin/bashRAN=1cat test.txt | while read CHESS;do  { while true;do    MD=echo $RAN|md5sum|cut -c1-10    if [[ \"$MD\" == \"$CHESS\" ]];then      echo $RAN      break    else      let RAN++    fi  done }&  waitdone

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

#!/bin/bashwhile :;dowho|grep \'hacker\' >> /var/log/login.logsleep 3done

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

#!/bin/bashNUM1=`cat /dev/urandom|tr -dc \'[:digit:]\'|head -c1`while :;doread -p \"Please input a digit[0-9]: \" NUM2if [ $NUM2 -eq $NUM1 ];thenecho -e \"\\e[1;$[RANDOM%7+31]mCongratulations, got it right.\\e[0m\"exit 2elif [ $NUM2 -lt $NUM1 ];thenecho -e \"\\e[1;$[RANDOM%7+31]mSorry,is too lower.\\e[0m\"elseecho -e \"\\e[1;$[RANDOM%7+31]mSorry,is too higher.\\e[0m\"fidone

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

#!/bin/bashread -p \"Please input a little filename: \" FILESwhile [ -n \"$FILES\" ];doecho -e \"\\e[1;33mLines are `cat $FILES |wc -l`.\\e[0m\"breakdone

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

#!/bin/bashif [ $# -lt 2 ];thenecho at least 2 argumentexit 1fideclare -i bigdeclare -i smalldeclare -i fir=$#until [ $# = 0 ];doif [[ ! \"$1\" =~ ^[0-9]+$ ]];thenecho wrong number $1exitfiif [ $fir = $# ];thenlet big=$1let small=$1elseif [ $1 -gt $big ];thenlet big=$1elif [ $1 -lt $small ];thenlet small=$1fifishiftdoneecho the biggest number is : $bigecho the smallest unmber is: $small
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 作业–SHELL脚本编程练习答案(多版本)