练习1 写一个脚本,让用户输入几个文件,脚本能多将此几个文件归档压缩成一个文件。 #!/bin/bash read -p "please input three files:" FILE1 FILE2 FILE3 read -p "please input name:" DNAME tar -jcf /root/mscripts/cpios/${DNAME}.bz2 $FILE1 $FILE2 $FILE3 拓展: 用户自己指定压缩方式 [root@localhost mscripts]# cat lx26.sh #!/bin/bash read -p "please input three files:" FILE1 FILE2 FILE3 read -p "please input name:" DNAME read -p "please input your cmios chioce:" cpios case $cpios in gzip) tar -zcf /root/mscripts/cpios/${DNAME}.gz $FILE1 $FILE2 $FILE3 ;; bzip2) tar -jcf /root/mscripts/cpios/${DNAME}.bz2 $FILE1 $FILE2 $FILE3 ;; xz) tar -cf /root/mscripts/cpios/${DNAME}.tar $FILE1 $FILE2 $FILE3 xz /root/mscripts/cpios/${DNAME}.tar ;; *) echo "quit..." exit 9 esac 练习2 写一个脚本 计算1到100以内的整数和,要求用while语句。 [root@localhost mscripts]# cat lx25.sh #!/bin/bash declare -i I=1 declare -i SUM=0 while [ $I -le 100 ]; do let SUM+=$I let I++ done echo "the sum:$SUM." 练习3 写一个脚本 每5秒种监测下某一用户是否登录系统,如果登录就退出脚本; [root@localhost mscripts]# cat lx28.sh #!/bin/bash who | grep "bruce" &> /dev/null RETU=$? while [ $RETU -ne 0 ]; do echo "date
,user bruce no loged." sleep 5 who | grep "bruce" &> /dev/null RETU=$? done
echo "user bruce has loged." 练习4 写一个脚本 1)显示一个菜单给用户 d|D shou disk usages. m|M show memory usages. s|S show memory usages. *) quit 2) 当用户给定选项后显示相应的内容 [root@localhost mscripts]# cat lx29.sh #!/bin/bash cat << EOF d|D show disk usages. m|M show memory usages. s|S show swap usages. *) quit EOF read -p "please input your choice:" CHOICE case $CHOICE in d|D) df -h ;; m|M) free -m | grep "Mem" ;; s|S) free -m | grep "Swap" ;; *) echo "quit..." exit 9 esac
扩展: 当用户选择完成,显示相应信息后,不退出;而让用户再一次选择,再次显示相应内容,除了用户使用quit; [root@localhost mscripts]# cat lx30.sh
#!/bin/bash cat << EOF d|D show disk usages. m|M show memory usages. s|S show swap usages. *) quit EOF read -p "please input your choice:" CHOICE while [ $CHOICE != 'quit' ]; do case $CHOICE in d|D) df -h ;; m|M) free -m | grep "Mem" ;; s|S) free -m | grep "Swap" ;; *) echo "quit..." esac read -p "please input your choice:" CHOICE done