阿汤博客-承接中小企业服务器维护和网站维护,有意者可以联系博主!

Linux Shell脚本练习

学习笔记 76℃ 0评论

练习1:

1、添加3个用户user1,user2,user3,先判断用户是否存在,不存在而后再添加

2、显示当前系统上共有多少个用户

#!/bin/bash

for i in user1 user2 user3;do

! id $i &> /dev/null && useradd $i && echo $i | passwd –stdin $i &> /dev/null || echo "$i is exists"

done

sum=`wc -l /etc/passwd | cut -d' ' -f1`

echo "$sum /etc/passwd users"

练习2:

写一个脚本,完成如下功能;添加三个用户;求此三个用户的UID之和

#/usr/bash

for((i=1;i<=3;i++));do

username="user$i"

useradd "$username"

echo "$username" | passwd –stdin $username

num=$(id -u "$username")

let sum=sum+$num

done

echo $sum

练习3:

让centos用户登录时,提示其已经登录,并提示当前时间。

#!/bin/bash

echo "Welcome login!"

echo -n "NOW Time is: " 

date

echo -n "Login ip:"

who | awk 'END{print $5}' |tr "()" " "

练习4:

判定命令历史中历史命令的总条目是否大于1000;如果大于就显示“some command will gone”;否则显示“OK”

num=`history | tail -1 | awk '{print $1}'`

if [[ $num -gt 1000 ]];then

echo "OK!"

else

echo "Some command will gone"

fi

练习5:

给定一个用户,获取其mime警告期限;而判断用户mime使用期限是否已经小于警告期限(提示:计算方法,最长使用期限减去已经使用的天数即为剩余使用期限);如果小于,则显示“warning”;否则,就显示“OK”

#!/bin/bash

TODAY=`date +%s`

ZUIJIN=`tail -1 /etc/shadow | cut -d":" -f3`

SHIYONG=$[TODAY/(24*60*60) – $ZUIJIN]

ZUICHANG=`tail -1 /etc/shadow | cut -d":" -f5`

JINGAO=`tail -1 /etc/shadow | cut -d":" -f6`

SY=$[ $ZUICHANG-$SHIYONG ]

if [ $SY -gt $JINGAO ];then

echo "OK!"

else

echo "Warning!"

fi 

练习6:

给定一个文件,如果是一个普通文件,就显示之;如果是一个目录,亦显示之;否则,此为无法识别之文件。

#!/bin/bash

FILE=/etc/shadow2

if [ ! -e $FILE ];then

    echo "NO such file."

    exit 1

fi

if [ -e $FILE ];then

    echo "wenjian" 

elif [ -d $FILE ];then

    echo "mulu"

else

    echo "Unknown"

fi

练习7:

给脚本传递两个参数(整数);显示此两者之和,之积。

#/bin/bash

if [ $# -ne 2 ]; then

echo "Plese Enter Two AGE"

exit 2

fi

HE=$[ $1+$2 ]

JI=$[ $1*$2 ]

echo "$1 + $2=$HE"

echo "$1 * $2=$JI"

练习8:

传递一个用户名参数脚本,判断此用户的用户名跟其基本组的组名是否一致,并将结果显示出来

#!/bin/bash

if ! id $1 &>/dev/null;then

echo "NO such User"

exit 6

fi

G=`id -n -g $1`

if [ $G = $1 ];then

echo "yiyang"

else

echo " buyiyang"

fi

练习9:

传递三个参数给脚本,第一个为整数,第二个为算术运算符,第三个为整数,将计算结果显示出来,要求保留两位精度。如: ./calc.sh 5 / 2

#!/bin/bash

echo "scale=2;$1$2$3 "|bc

练习10:

传递三个参数给脚本,参数均为用户名。将此用户的账号信息提取出来后放置于/tmp/testusers.txt文件中,并要求每一行行首有行号。

#!/bin/bash

for i in [email protected];do

if ! id $i &>/dev/null;then

echo "$i Not User"

exit 6

fi

done

echo "1 $1" | tee -a /tmp/testuser.txt

echo "2 $2" | tee -a /tmp/testuser.txt

echo "3 $3" | tee -a /tmp/testuser.txt

#!/bin/bash

for i in [email protected];do

if ! id $i &>/dev/null;then

echo "$i Not User"

exit 6

fi

done

m=1

while (( $m<=$# ));do

    for i in [email protected];do

echo $m $i |tee -a /tmp/testusers.txt

let "m++"

    done

done

练习11:

1.判断当前主机的CPU生产商,其信息在/proc/cpuinfo文件中vendor id 一行中。

2.如果其生产商为AuthenticAMD,就显示为AMD公司

3.如果其生产商为GenuineIntel,就显示为Intel公司

4.否则,就说其为非主流公司

#!/bin/bash

CPU=`grep "vendor_id" /proc/cpuinfo | head -1 | awk '{print $3}'`

if [ $CPU == "AuthenticAMD" ];then

    echo "AMD"

elif [ $CPU == "GenuineIntel" ]

    echo "Intel"

else

    echo "Feizhuliu"

fi  

练习12:

给脚本传递三个参数,判断其中 的最大数和最小数,并显示出来

#!/bin/bash

MAX=0

for i in [email protected];do

    if [ $i -gt $MAX ];then

        MAX=$i

    fi

done

    echo Max is $MAX

SMALL=0

NUM=0

for i in [email protected];do

    let NUM++

    [ $NUM -eq 1 ]&& SMALL=$i

    if [ $i -lt $SMALL ];then

        SMALL=$i

    fi

done

    echo Small is $SMALL

练习12:

写一个脚本:只接收参数start,stop,restrart,status其中之一。

#!/bin/bash

case $1 in

'start')

    echo "start!";;

'stop')

    echo "stop!";;

'restart')

    echo "restart!";;

'staus')

    echo "staus!";;

*)

    echo `basename $0` "(start|stop|restrart|status)"

esac

练习13:

写一个脚本,可以接受选项及参数,而后能获取每一个选项,及选项的参数;并能根据选项参数做出特定的操作,比如:adminusers.sh –add tom,jerry –del tom,blair -v|–verbose -h|–help

#!/bin/bash

DEBUG=0

ADD=0

DEL=0

for i in `seq 0 $#`;do

if [ $# -gt 0 ];then

case $1 in

-v|–verbose)

    DEBUG=1

    shift ;;

-h|–help)

    echo "Usage: `basename $0` –add USER_LIST –del USER_LIST -v|–verbose -h|–help"

    exit 0 ;;

–add)

    ADD=1

    USERS=$2

    shift 2 ;;

–del)

    DEL=1

    USERS=$2

    shift 2 ;;

*)

    echo "Usage: `basename $0` –add USER_LIST –del USER_LIST -v|–verbose -h|–help"

    exit 6 ;;

esac

fi

done

if [ $ADD -eq 1 ];then

    for user in `echo $USERS | tr "," " "`;do

        if id $user &>/dev/null;then

             [ $DEBUG -eq 1 ] && echo "$user exists"

        else

            useradd $user

            echo $user | passwd –stdin $user &>/dev/null

            [ $DEBUG -eq 1 ] && echo "Add user:$user finished! "

        fi

    done

fi

if [ $DEL -eq 1 ];then

    for user in `echo $USERS | tr "," " "`;do

        if id $user &>/dev/null;then

             userdel -rf $user &>/dev/null

             [ $DEBUG -eq 1 ] && echo "$user Delete finished!"

        else

            [ $DEBUG -eq 1 ] && echo "$user Not exist. "

        fi

    done

fi

练习14:

写一个脚本showlogged.sh,其中语法格式为:showlogged.sh -v -c -h|–help

其中,-h选项只能单独使用,用于显示帮助信息;-c选项时,显示当前系统上登录的所有用户数;如果同时使用了-v选项,则即显示同时登录的用户数,又显示登录的用户的相关信息;如:

logged users: 4

they are:

root  pts/0    2016-10-09 12:38 (171.221.140.180)

root  pts/2    2016-10-09 13:15 (171.221.140.180)

root  pts/3    2016-10-09 13:16 (171.221.140.180)

#!/bin/bash

declare -i DEBUG=0

declare -i USER=0

for i in `seq 1 $#`;do

if [ $# -gt 0 ];then

case $1 in

-v)

DEBUG=1

shift;;

-h|–help)

echo "Usage:`basename $0` -v -c -h|–help"

exit 0;;

-c)

USER=1

shift ;;

*)

echo "Usage:`basename $0` -v -c -h|–help"

exit 7;;

esac

fi

done

if [ $USER -eq 1 ];then

    num=`who | wc -l`

    echo "Logged users:$num"

    if [ $DEBUG -eq 1 ];then

        echo "They are:" 

        who

    fi

fi

练习15:

1.设定变量FILE的值为/etc/passwd

2.依次向/etc/passwd中的每个用户问好,并显示对方的shell,如:Hello, root ,your shell: /bin/bash

3.统计一共有多少个用户

#!/bin/bash

LIST=`awk -F: '{print $1}' /etc/passwd`

for i in $LIST;do

    BS=`grep "^$i\>" /etc/passwd | awk -F: '{print $7}'`

    echo "Hello,$i Your bash is $BS"

done

sum=`wc -l /etc/passwd | cut -d' ' -f1`

echo "$sum /etc/passwd users"

练习16:

1、添加10个用户user1到user10,但要求只有用户不存在的情况下才添加。

#!/bin/bash

for m in {1..10};do

i=user$m

! id $i &> /dev/null && useradd $i && echo $i | passwd –stdin $i &> /dev/null || echo "$i is exists"

done

2、接收一个参数:add:添加user1-user10  ; del:删除user1-user10 ; 其他:退出

#!/bin/bash

if [[ $1 != add && $1 != del ]];then

    echo "Plese ENter add OR del"

    echo "exit…"

    exit 6

fi

for i in {1..10};do

    NAME=user$i

    if [[ $1 == add ]];then

        useradd $NAME &>/dev/null && echo $NAME | passwd –stdin $NAME&>/dev/null && echo "$NAME add OK!" || echo "$NAME is Exists"

    elif [[ $1 == del ]];then

        userdel -rf $NAME &>/dev/null&& echo "$NAME delete OK!" || echo "$NAME no Such"

    else

        echo "ARG Error!"    

    fi

done

练习17;

1.计算100以内所有能被3整除的正整数的和。

#!/bin/bash

declare -i sum=0

for i in {1..100};do

    if (($i%3==0));then

        let sum=$[$sum+$i]

    fi

done

    echo $sum 

2.计算100以内所有奇数的和以及所有偶数的和

#!/bin/bash

for i in {1..100};do

if (($i%2==0));then

let sum=$sum+$i

fi

done

echo $sum

#!/bin/bash

for i in {1..100};do

if (($i%2==1));then

let sum=$sum+$i

fi

done

echo $sum

3.计算100以内所有正整数的和。

#!/bin/bash

declare -i i=1

declare -i num=0

while [ $i -le 100 ];do

let sum=$sum+$i

let i++

done

echo $sum

4.分别使用for,while,until实现分别求100以内所有偶数之和,100以内所有奇数之和;

#!/bin/bash

for m in {1..100}

do

    if(($m%2==0));then

     let num=$num+$m

    fi

done

    echo $num

#!/bin/bash

for m in {1..100}

do

    if(($m%2==1));then

     let num=$num+$m

    fi

done

    echo $num

练习18:

写一个脚本,分别显示当前系统上所有默认shell为bash的用户和默认shell为/sbin/nologin的用户,并统计各类shell下的用户总数。显示结果如:

bash,3users,they are: root,redhat,gentoo

nologin,2users ,they are: bin ftp

#!/bin/bash

BASH_array=(`grep "\<bash\>$" /etc/passwd | cut -d":" -f1`)

BASH_num=`grep -c "\<bash\>$" /etc/passwd`

NOLOGIN_array=(`grep "\<nologin\>$" /etc/passwd | cut -d":" -f1`)

NOlOGIN_num=`grep -c "\<nologin\>$" /etc/passwd`

echo "bash,${BASH_num} users, they are:${BASH_array[@]}"

echo "nologin,${NOlOGIN_num} users, they are:${NOLOGIN_array[@]}"

练习19:

写一个脚本

1.显示一个菜单给用户:

d|D) show disk usages.

m|M) show memory usages

s|S) show swap usages

*) quit

2.当用户给定选项后显示相应的内容

扩展:当用户选择完成,显示相应的信息后,不退出;而让用户再一次选择,再次显示相应内容;除了用户使用quit

#!/bin/bash

cat << EOF

d|D) show disk usages.

m|M) show memory usages.

s|S) show swap usages.

*) quit.

EOF

read -p"Please Choice:" CHOICE

while [ $CHOICE != 'quit' ];do

    case $CHOICE in

    d|D)

        echo -e "\033[32mdisk usage: \033[0m"

        df -Ph;;

    m|M)

        echo -e "\033[33mMemory usage: \033[0m"

        free -m |grep "Mem";;

    s|S)

        echo -e "\033[34mSwap usage: \033[0m"

        free -m |grep "Swap";;

    *)

        echo -e "\033[31mUnknown! \033[0m"

    esac

    read -p"Please Choice:" CHOICE

done

练习20:

1.打印99乘法表。

#!/bin/bash

for m in {1..9};do

    for((n=1;n<=m;n++));do

        echo -n "$n*$m = $(($m*$n)) " 

    done

    echo -e "\n"

done

2.打印逆序的九九乘法表

#!/bin/bash

for m in {9..1};do

    for((n=1;n<=m;n++));do

        echo -n "$n*$m = $(($m*$n)) " 

    done

    echo -e "\n"

done

练习21:

利用RANDOM生成10个随机数,并找出其中最大值,和最小值。

#!/bin/bash

declare -i max=0

declare -i min=0

for i in {1..10};do

    rand=$RANDOM

    [ $i -eq 1 ] && min=$rand

    if [ $i -le 9 ];then

        echo -n "$rand,"

    else

        echo $rand

    fi

    [ $rand -gt $max ] && max=$rand

    [ $rand -lt $min ] && min=$rand

done

    echo "MAX:$max"

    echo "MIN:$min"

练习22:

通过ping命令测试192.168.0.151到192.168.0.254之间的所有主机是否在线,如果在线,就显示“ip is up”,其中的IP要换为真正的IP地址,且以绿色显示;如果不在线,就显示“ip is down”,其中的IP地址换为真正的IP地址,且以红色显示。要求:分别饰演while,until ,for(两种形式)循环实现。

#!/bin/bash

declare -i LAST=150

while [ $LAST -le 254 ];do

#until [ $LAST -gt 254 ];do

IP=192.168.0.$LAST

if ping -c 1 -W 1 $IP &> /dev/null;then

echo -e "IP:\033[32m $IP \033[0m is up" 

else 

echo -e "IP:\033[31m $IP \033[0m is down" 

fi

let LAST++

done

#!/bin/bash

for i in {150..254};do

#for ((i=150;i<=254;i++));do

IP=192.168.0.$i

if ping -c 1 -W 1 $IP &> /dev/null;then

echo -e "IP:\033[32m $IP \033[0m is up" 

else 

echo -e "IP:\033[31m $IP \033[0m is down" 

fi

done

练习23:

写一个脚本(前提:请为虚拟机新增一块硬盘,架设它为/dev/sdb),为指定的硬盘创建分区,

1.列出当前系统上所有的磁盘,让用户选择,如果选择quit则退出脚本;如果用户选择错误,就让用户重新选择

2.当用户选择后,提醒用户确认接下来的操作可能会损坏数据,并请用户确认,如果用户选择y就继续,n就退出,否则,让用户重新选择

3.抹除那块硬盘上的所有分区(提示:抹除所有分区后执行sync命令,并让脚本睡眠3秒种后再分区);并为其创建三个主分区,第一个为20M,第二个为512M,第三个为128M,且第三个为swap分区类型:(提示:将分区命令通过echo传送给fdisk即可实现)

#!/bin/bash

echo "Initial a Disk…"

echo -e "\033[31mWarning:Data will be lost!!!\033[0m"

fdisk -l | grep "Disk /dev/[vhs]d[a-z]" | awk -F: '{split($1,D," ");printf"Disk%d:%s\n",NR,D[2]}'

echo -en "\033[31mYour Choice:\033[0m"

read dk

if [ $dk == 'quit' ];then

    echo "Exiting…"

    exit 5

fi

until fdisk -l | grep "Disk /dev/[vhs]d[a-z]" | awk -F: '{print $1}' | grep "Disk $dk$" &>/dev/null ;do

echo -en "\033[31mChoose wrong, please choose again:\033[0m"

read dk

if [ $dk == 'quit' ];then

echo "Exiting…"

exit 5

fi

done

echo -en "\033[31mClear all data,Please Choice y or n:\033[0m"

read choice

until [ $choice == 'y' -o $choice == 'n' ];do

echo -en "\033[31mChoose wrong, please choose y or n:\033[0m"

read choice

done

if [ $choice == 'n' ];then

echo "Quiting…"

exit 6

else

for i in `df -lh | grep "/dev/sdc" | awk '{print $1}'`;do

fuser -km $i

umount $i &>/dev/null

echo -e "\033[31m$i umount finish!\033[0m"

done

dd if=/dev/zero of=$dk bs=512 count=1 &>/dev/null

sync 

sleep 3

echo "

n

p

1

+20M

n

p

2

+512M

n

p

3

+128M

t

3

82

w" | fdisk $dk &>/dev/null

partprobe $dk &>/dev/null

sync

sleep 2 

mke2fs -j ${dk}1 &>/dev/null

echo -e "\033[32m${dk}1 formatting finish!\033[0m"

mke2fs -j ${dk}2 &>/dev/null

echo -e "\033[32m${dk}2 formatting finish!\033[0m"

mkswap ${dk}3 &>/dev/null

echo -e "\033[32m${dk}3 formatting finish!\033[0m"

fi

fdisk -l $dk

swapon ${dk}3

练习24:

写一个脚本,完成以下功能:(说明:此脚本能于同一个repo文件中创建多个yum源的指向)

1.接受一个文件名做为参数,此文件存放至/etc/yum.repos.d目录中,且文件名以.repo为后缀

2.在脚本中,提醒用户输入repo id ;如果为quit,则退出脚本;否则,继续完成下面的步骤:

3.repo name以及baseurl的路径,而后以repo文件的格式将其保存至指定的文件中;

4.enabled默认为1,而gpgcheck默认设定为0

5.此脚本会循环执行多次,除非用户为repo id指定为quit

#!/bin/bash

REPO=/etc/yum.repos.d/$1

if [ -e $REPO ];then

echo "The $1 Exist!"

exit 3

fi

echo -en "\033[32mPlease Enter Repo Id:\033[0m"

read REPOID

until [ $REPOID == "quit" ];do

echo "[$REPOID]" >> $REPO

echo -en "\033[34mPlease Enter Repo Name:\033[0m"

read REPONAME

echo "name=$REPONAME" >> $REPO

echo -en "\033[34mPlease Enter baseurl:\033[0m"

read BASEURL

echo "baseurl=$BASEURL" >> $REPO

echo -e "enabled=1\ngpgcheck=0" >>$REPO

echo -en "\033[32mPlease Enter Repo Id:\033[0m"

read REPOID

done

echo "quit…"

exit 0

练习25:

1.判断一个值得的bash脚本是否有语法错误:如果有错误,则提醒用户键入Q或者q无视错误并退出,其他任何键可以通过vim打开这个值得的脚本

2.如果用户通过vim打开编辑后保存并退出时任然有错误,则重复第一步中的内容:否则,就正常关闭退出。

#!/bin/bash

until `bash -n $1 &>/dev/null`;do

echo -ne "\033[31mSyntax error ,[Q|q] to quit bash; others for vim $1: \033[0m"

read INPUT

if [ $INPUT != "q" -a $INPUT != "Q" ];then

vim $1

continue

else

echo "quit…!"

exit 5

fi

done

echo "$1 bash is OK!"

#!/bin/bash

until `bash -n $1 &>/dev/null`;do

echo -ne "\033[31mSyntax error ,[Q|q] to quit bash; others for vim $1: \033[0m"

read CHOSE

case $CHOSE in

Q|q)

echo "Syntax error ,quit!"

exit 3;;

*)

vim $1;;

esac

done

echo "$1 bash is OK!"

练习26:

判定192.168.0.200-192.168.0.254之间的主机哪些在线。要求:

1.使用函数来实现一台主机的判断过程

2.在主程序中来调用此函数判定指定范围内的所有主机的在线情况

#!/bin/bash

PING(){

if ping -c 1 -W 1 $1 &>/dev/null;then

return 0

else

return 1

fi

}

for i in {200.254};do

IP=192.168.0.$i

PING $IP

if [ $? -eq 0 ];then

echo -e "IP:\033[32m $IP \033[0m is up" 

else

echo -e "IP:\033[31m $IP \033[0m is down" 

    fi

done

练习27:

使用函数完成

1.函数能够接受一个参数,参数为用户名;判断一个用户存在,如果存在就返回此用户的shell和UID;并返回正常状态值;如果不存在就说此用户不存在,并返回错误状态值

2.在主程序中调用函数

扩展1:在主程序中,让用户自己输入用户名后,传递函数来进行判断;

扩展2:在主程序中,输入用户名判断后不退出脚本,而是提示用户继续输入下一个用户名;如果用户输入的用户不存在,请用户重新输入,但如果用户输入的是q或Q就退出。

#!/bin/bash

USERID(){

if id $1&>/dev/null;then

return 0

else

return 1

fi

}

echo -ne "\033[32mPlease input UserName:\033[0m"

read USERNAME

while :;do

USERID $USERNAME

RETU=$?

if [ $USERNAME == "Q" -o $USERNAME == "q" ];then

echo -e "\033[35mquit…\033[0m"

exit 6

elif [ $RETU -eq 1 ];then

echo -ne "\033[31mUsers not exits!Please agin input:\033[0m"

read USERNAME

continue

else

cat /etc/passwd | grep "$USERNAME" | awk -F: '{printf "%s Uid:%d shell:%s\n",$1,$3,$NF}' 

fi

echo -ne "\033[32mPlease input UserName:\033[0m"

read USERNAME 

done

练习28:

服务样例脚本

#!/bin/bash:

#

# chkconfig:2345 45 55

# description:This is my services!

FILE=/var/lock/subsys/mylinux

NAME=`basename $0`

STATUS(){

if [ -e $FILE ];then

echo -e "\033[32m$NAME is running… \033[0m"

else

echo -e "\033[31m$NAME is stoped\033[0m"

fi 

}

USAGE(){

echo "/etc/init.d/$NAME {start|stop|restart|status}"

}

case $1 in

start)

echo "starting…"

touch $FILE;;

stop)

echo "stoping…"

rm -f $FILE &>/dev/null;;

restart)

echo "restarting…";;

status)

STATUS ;;

*)

USAGE;;

esac

练习29:

复制命令以及命令依赖的库文件到新的根目录。

#!/bin/bash

MYROOT=/www/myroot

cplib(){

libdir=${1%/*}

newlib=$MYROOT$libdir

[ ! -d $newlib ] && mkdir -p $newlib

[ ! -e $MYROOT$1 ] && cp $1 $newlib && echo -e "\033[35m$1 copy finished!\033[0m"

}

cpcmd(){

cmddir=${1%/*}

newcmd=$MYROOT$cmddir

[ ! -d $newcmd ] && mkdir -p $newcmd

[ ! -e $MYROOT$1 ] && cp $1 $newcmd

for i in `ldd $1 | grep -o "/.*lib\(64\)\?/[^[:space:]]\+"`;do

cplib $i

done

}

echo -ne "\033[34mPlease input Command:\033[0m"

read CMD

until [ $CMD == 'q' ];do

! which $CMD &>/dev/null && echo -ne "\033[31mCommand not exist,Please againe input:\033[0m" && read CMD && continue

COMMAND=`which $CMD | grep -v "alias" | grep -o "[^[:space:]]\+"`

cpcmd $COMMAND

echo -e "\033[32m$COMMAND copy finished!\033[0m"

echo -ne "\033[33mPlease input Command:\033[0m"

read CMD

done

练习30:

系统函数库样本。

#!/bin/bash

SCREEN=`stty -F /dev/console size 2>/dev/null`

COLUMNS=${SCREEN#* }

[ -z $COLUMNS ]&& COLUMNS=80

SPA_COL=$[$COLUMNS-14]

RED='\033[1;31m'

GREEN='\033[1;32m'

BLUE='\033[1;34m'

NORMAL='\033[0m'

success(){

string=$1

RT_SPA=$[$SPA_COL-${#string}]

echo -n $string

for i in `seq 1 $RT_SPA`;do

echo -n " "

done

echo -e "[ ${GREEN}OK${NORMAL} ]"

}

failde(){

string=$1

RT_SPA=$[$SPA_COL-${#string}]

echo -n $string

for i in `seq 1 $RT_SPA`;do

echo -n " "

done

echo -e "[ ${RED}FAILED${NORMAL} ]"

}

练习31:

信号捕捉

#!/bin/bash

TRAP(){

rm -rf /var/tmp/test

echo "quit and cleaning"

}

trap 'TRAP;exit 5' INT

mkdir -p /var/tmp/test

while true;do

file=/var/tmp/test/file-`date +%H%M%S`  

touch $file

echo "Touch $file ok!"

sleep 2

done

练习32:

1.数组的元素个数为1-39

2.数组元素不能相同

3.显示此数组各元素的值

#!/bin/bash

read -p "input numbers[1-39]:" NUM

declare -a ARRAY

BJ(){

for j in `seq 0 $[${#ARRAY[@]}-1]`;do

if [ $1 -eq ${ARRAY[$j]} ];then

return 1

fi

done

return 0

}

for i in `seq 0 $[$NUM-1]`;do

while true;do

RAND=$[$RANDOM%40]

BJ $RAND

if [ $? -eq 0 ];then

break 

fi

done

ARRAY[$i]=$RAND

echo "${ARRAY[$i]}"

done

练习33:

bash脚本使用选项

#!/bin/bash

while getopts ":d:" SWITCH;do

case $SWITCH in

d)

DESC=$OPTARG;;

\?)

echo "Usage:`basename $0` [-d descriprion] FILENAME";;

esac

done

shift $[$OPTIND-1]

if ! grep "[^[:space:]]" $1 &> /dev/null;then

cat > $1 << EOF

#!/bin/bash

# Name:`basename $1`

# Description:$DESC

# Author:adm5.cn

# Version:0.0.1

# Datetime: `date "+%F %T"`

# Usage:`basename $1`

#

EOF

fi

vim + $1

until bash -n $1 &> /dev/null;do

echo -ne "\033[31mSyntax error ,[Q|q] to quit `basename $0`; others for vim $1: \033[0m"

read CHOSE

case $CHOSE in

Q|q)

echo "Syntax error ,quit!"

exit 3;;

*)

vim $1;;

esac

done

echo "$1 bash grammar is OK!"

chmod +x $1

练习34:

写一个脚本getinterface.sh,脚本可以接受选项(i,I,a),完成以下任务

1.使用以下形式:getinterface.sh [-i interface|-I IP|-a]

2.当用户使用-i选项时,显示其指定网卡的IP地址

3.当用户使用-I选项时,显示其后面的IP地址所属的网络接口

4.当用户单独使用-a选项时,显示所有网络接口及其IP地址(除lo除外)

#!/bin/bash

# Name:getinterface.sh

# Description: Get ehternet information

# Author:amd5.cn

# Version:0.0.1

# Datetime: 2016-11-28 23:12:23

# Usage:getinterface.sh [-i INTERFACE|-I IP|-a ]

#

GETIP(){

if ! ifconfig | grep -o "^[^[:space:]]\+" | grep $1 &>/dev/null;then

echo "Wrong ehtercard!"

exit 5

fi

IP=`ifconfig $1 | grep -o "inet addr:[0-9\.]\+" | cut -d":" -f2`

}

GETNET(){

if ! ifconfig | grep -o "inet addr:[0-9\.]\+" | cut -d":" -f2 | grep $1 &>/dev/null;then

echo "Wrong IP!"

exit 6

fi

NETWORK=`ifconfig | grep -B 1 "inet addr:$1" | grep -o "^[^[:space:]]\+"`

}

GETALL(){

for i in `ifconfig | grep -o "^[^[:space:]]\+" | grep -v "lo"`;do

GETIP $i

echo "$i:$IP"

done

}

USAGE(){

echo "usage:`basename $0`[-i INTERFACE|-I IP|-a ]"

}

while getopts ":i:I:a" OPT;do

case $OPT in

i)

GETIP $OPTARG

echo -e "$OPTARG:\033[32;1m$IP\033[0m";;

I)

GETNET $OPTARG

echo -e "$OPTARG:\033[32;1m$NETWORK\033[0m";;

a)

GETALL;;

\?)

USAGE;;

esac

done

转载请注明:阿汤博客 » Linux Shell脚本练习

喜欢 (0)or分享 (0)