首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 其他相关 >

shell脚本例证

2013-09-08 
shell脚本例子1.模拟linnux登录shell#/bin/bashecho -n login: read nameecho -n password:read passw

shell脚本例子

1.模拟linnux登录shell

#/bin/bash
echo -n "login:" 
read name
echo -n "password:"
read passwd
if [ $name = "cht" -a $passwd = "abc" ];then
echo "the host and password is right!"
else echo "input is error!"
fi

2.比较两个数大小

#/bin/bash
echo "please enter two number"
read a
read b
if test $a -eq $b
then echo "NO.1 = NO.2"
elif test $a -gt $b
then echo "NO.1 > NO.2"
else echo "NO.1 < NO.2" 
fi

3.查找/root/目录下是否存在该文件

#/bin/bash
echo "enter a file name:"
read a
if test  -e /root/$a 
then echo "the file is exist!"
else echo "the file is not exist!"
fi

4.for循环的使用

#/bin/bash
clear
for num in 1 2 3 4 5 6 7 8 9 10
do
    echo "$num"
done

5.

#/bin/bash
echo "Please enter a user:"
read a
b=$(whoami)
if test $a = $b
then echo "the user is running."
else echo "the user is not running."
fi

6.删除当前目录下大小为0的文件

#/bin/bash
for filename in `ls`
do
    if test -d $filename
    then b=0
    else    
       a=$(ls -l $filename | awk '{ print $5 }')
            if test $a -eq 0
             then rm $filename
             fi
        fi      
done

7.如果/export/um_lpp_source下有文件,那么将其文件系统大小改为3G

 #/bin/bash
while line=`ls /export/um_lpp_source`
do
        if test $line=""
        then  echo "NULL"
             sleep 1
    else echo $line
                chfs -a size=3G /export/um_lpp_source
                 exit 0
        fi
done

 

8.测试IP地址

#/bin/bash
for i in  1 2 3 4 5 6 7 8 9 
do
    echo "the number of $i computer is "
    ping -c 1 192.168.0.$i
done

9.如果test.log的大小大于0,那么将/opt目录下的*.tar.gz文件

 #/bin/sh
a=2
while name="test.log"
do
        sleep 1
        b=$(ls -l $name | awk '{print $5}')
        if test $b -ge $a
        #then echo "OK"
    then `cp /opt/*.tar.gz .`
        exit 0
        fi
done

10.打印读取的内容,为下面的例子做准备

#/bin/bash
while read name
do
echo $name
done

11.从0.sh中读取内容并打印

#/bin/bash
while read line
do
    echo $line
done < 0.sh

12.读取a.c中的内容并做加1运算

#/bin/bash
test -e a.c
while read line
do
    a=$(($line+1))
done < a.c
echo $a

13.普通无参数函数

#/bin/bash
p ()
{
    echo "hello"
}
p

14.给函数传递参数

#/bin/bash
p_num ()
{
    num=$1
    echo $num
}
for n in $@
do
    p_num $n
done

15.创建文件夹

#/bin/bash
while :
do
    echo "please input file's name:"
    read a
    if test -e /root/$a
    then
         echo "the file is existing Please input new file name:"
    else
        mkdir $a
        echo "you aye sussesful!"
        break 
    fi
done

16.获取本机IP地址

#/bin/bash
ifconfig | grep "inet addr:" | awk '{ print $2 }'| sed 's/addr://g'

17.查找最大文件

#/bin/bash
a=0
for  name in *.*
do
     b=$(ls -l $name | awk '{print $5}')
    if test $b -ge $a
    then a=$b
         namemax=$name
     fi
done
echo "the max file is $namemax"

18.查找当前网段内IP用户,重定向到ip.txt文件中

#/bin/bash
a=1
while :
do
    a=$(($a+1))
    if test $a -gt 255
    then break
    else
        echo $(ping -c 1 192.168.0.$a | grep "ttl" | awk '{print $4}'| sed 's/://g')
        ip=$(ping -c 1 192.168.0.$a | grep "ttl" | awk '{print $4}'| sed 's/://g')
        echo $ip >> ip.txt
    fi
done

19.打印当前用户

#/bin/bash
echo "Current User is :"
echo $(ps | grep "$$" | awk '{print $2}')

20.case语句练习

#!/bin/bash
clear
echo "enter a number from 1 to 5:"
read num
case $num in
    1) echo "you enter 1"
    ;;
    2) echo "you enter 2"
    ;;
    3) echo "you enter 3"
    ;;
    4) echo "you enter 4"
    ;;
    5) echo "you enter 5"
    ;;
    *) echo "error"
    ;;
esac

21.yes/no返回不同的结构

#!/bin/bash
clear
echo "enter [y/n]:"
read a
case $a in
    y|Y|Yes|YES) echo "you enter $a"
    ;;
    n|N|NO|no) echo "you enter $a"
    ;;
    *) echo "error"
    ;;
esac

22.

 

 

23.内置命令的使用

#/bin/bash

    clear
        echo "Hello, $USER"
        echo
        
        echo "Today 's date id `date`"

        echo

        echo "the user is :"
        who
        echo

        echo "this is `uname -s`"
        echo

        echo "that's all folks! "

24.

 

 

25.

#/bin/bash

26.打印无密码用户

#/bin/bash
echo "No Password User are :"
echo $(cat /etc/shadow | grep "!!" | awk 'BEGIN { FS=":" }{print $1}')

27.

#/bin/bash

    clear
        echo "Hello, $USER"
        echo
        
        echo "Today 's date id `date`"

        echo

        echo "the user is :"
        who
        echo

        echo "this is `uname -s`"
        echo

        echo "that's all folks! "



练习一:写一个脚本
       1.设定变量FILE的值为/etc/passwd
       2.依次向/etc/passwd中的每个用户问好,并且说出对方的ID是什么
        形如:(提示:LINE=`wc -l /etc/passwd | cut -d" " -f1`)
         Hello,root,your UID is 0.
       3.统计一个有多少个用户
     答案一:#!/bin/bash
           file="/etc/passwd"
           LINES=`wc -l $file | cut -d" " -f1`
           for I in `seq 1 $LINES`;do
           userid=`head -$I $file | tail -1 |cut -d: -f3`
           username=`head -$I $file | tail -1 |cut -d: -f1`
           echo "hello $username,your UID is $userid"
           done
           echo "there are $LINES users"
     答案二:#!/bin/bash
           file=/etc/passwd
           let num=0
           for I in `cat $file`;do
           username=`echo "$I" | cut -d: -f1`
           userid=`echo "$I" | cut -d: -f3`
           echo "Hello,$username,your UID is $userid"
           num=$[$num+1]
           done
           echo "there are $num users"
练习二:写一个脚本
      1.切换工作目录至/var
      2.依次向/var目录中的每个文件或子目录问好,形如:
        (提示:for FILE in /var/*;或for FILE in `ls /var`;)
        Hello,log
      3.统计/var目录下共有多个文件,并显示出来
  答案:#!/bin/bash
         cd /var
         let num=0
         for I in `ls /var/*`;do
         echo "hello $I"
         num=$[$num+1]
         done
         echo "the number of files is $num"
练习三:写一个脚本
      1.设定变量file的值为/etc/passwd
      2.使用循环读取文件/etc/passwd的第2,4,6,10,13,15行,并显示其内容
      3.把这些行保存至/tmp/mypasswd文件中
  答案:#!/bin/bash
       file="/etc/passwd"
       for I in 2 4 6 10 13 15;do
       exec 3>/tmp/mypasswd
       line=`head -$I $file | tail -1`
       echo "$line"
       echo "$line" >&3
       exec 3>&-
       done练习四:写一个脚本       传递两个整数给脚本,让脚本分别计算并显示这两个整数的和,差,积,商
        答案如下:vim test.sh
                   #!/bin/bash
                    echo "first number $1"  (表示输出第一个数)                    echo "second number $2" (表示输出第二个数)
                    echo " $(($1+$2))"      (输出两数之和)
                    echo "$[$1-$2]"         (输出两数之差)
                    echo "$[$1*$2]"         (输出两数之积)                    echo "$[$1/$2]"         (输出两数之商)
                    :wq                    (表示保存并退出vi编辑器)
                    chmod +x test.sh       (给test.sh执行的权限)
                    ./test.sh 2 3          (传递两个参数并执行脚本     作业一:写一个脚本:       1.创建目录/tmp/scripts       2.切换工作目录至此目录中       3.复制/etc/pam.d目录至当前目录,并重命名为test       4.将当前目录的test及其里面的文件和子目录的属主改为redhat       5.将test及其子目录中的文件的其它用户的权限改为没有任何权限   答案:
       #!/bin/bash
       mkdir -v /tmp/scripts
       cd /tmp/scripts
       cp -r /etc/pam.d ./test
       chown -R redhat ./test
       chmod -R o=--- ./test作业二:写一个脚本       1.显示当前系统日期和时间,而后创建目录/tmp/lstest       2.切换工作目录至/tmp/lstest       3.创建目录a1d,b56e,6test       4.创建空文件xy,x2y,732       5.列出当前目录下以a,x或者6开头的文件或目录       6.列出当前目录下以字母开头,后跟一个任意数字,而后跟任意长度字符的文件或目录   答案:
       #!/bin/bash
       date
       mkdir -pv /tmp/lstest
       cd /tmp/lstest
       mkdir a1d b56e 6test
       touch xy x2y 732
       ls [ax6]*
       ls [[:alpha:]][[:digit:]]*
            
作业三:写一个脚本
        添加10个用户user1到user10,但要求只有用户不存在的情况下才能添加
  答案:
       #!/bin/bash
       for I in `seq 1 10`;do
       cut -d: -f1 /etc/passwd |grep "user$I" 2>>/tmp/etc.err || useradd user$I
       done
作业四:写一个脚本
       通过ping命令测试192.168.0.151到192.168.0.254之间的所有主机是否在线
       如果在线,就显示“ip is up”
       如果不在线,就显示“ip is down”
      答案: #!/bin/bash
       for I in `seq 151 254`;do
       ping -c1 -w1 192.168.0.$I &>/dev/null && echo "192.168.0.$I is up" ||        echo "192.168.0.$I is down"
       done



1. 写一个脚本,利用循环计算10的阶乘

#!/bin/sh

 

factorial=1

 

for a in `seq 1 10`

do

        factorial=`expr $factorial \* $a`

done

 

echo "10! = $factorial"


注:上面有一行,for a in `seq 1 10`,其中seq 1 10 , 即列出现1到10之间所有的数字,这一行也可改为:for a in "1 2 3 4 5 6 7 8 9 10"

2. 写一个脚本,执行后,打印一行提示“Please input a number:",要求用户输入数值,然后打印出该数值,然后再次要求用户输入数值。直到用户输入"end"停止。

#!/bin/sh

 

unset var

 

while [   "$var" != "end" ]

do

      echo -n "please input a number: "

      read var

      if [ "$var" = "end" ]

      then

          break

      fi

      echo "var is $var"

done

 

3. 写一个脚本,利用循环和continue关键字,计算100以内能被3整除的数之和

#!/bin/sh

 

sum=0

for a in `seq 1 100`

do

      if [ `expr $a % 3` -ne 0 ]

      then

            continue

      fi

      echo $a

      sum=`expr $sum + $a`

done

 

echo "sum = $sum"

 

4.一个函数,利用shift计算所有参数乘积,假设参数均为整数( 特殊变量$# 表示包含参数的个数)

#! /bin/sh

 

result=1

while [ $# -gt 0 ]

do

      result=`expr $result \* $1`

      shift

done

echo $result

 

 

5.写一个脚本,可以根据参数文件名,以正确的参数调用tar来解压缩tar.gz或tar.bz2文件。

#!/bin/sh

 

case ${1##*.tar.} in

      bz2)

          tar jxvf $1

          ;;

      gz)

          tar zxvf $1

          ;;

      *)

          echo "wrong file type"

esac

 

6.写一个脚本以方便用户查询rpm的相关信息。这个脚本首先提示用户选择查询依据,比如文件名,包名,全部等。然后提示用户选择查询信息,比如包名,包里所包含的所有文件,包的信息等。然后询问是否继续查询,是则循环刚才的过程,否则退出。

#!/bin/sh

RPM=/bin/rpm

option="-q"

 

while true

do

        echo "what to query?"

        select var in   "All" "file" "package name"

        do

               case $var in

               All)

                       option=$option"a"

                       break

                      ;;

               file)

                       echo -n "please input file name: "

                       option=$option"f"

                       read argument

                       break

                      ;;

                package\ name)

                       echo -n "please input package name: "

                       read argument

                       break

                      ;;

               *)

                       echo "please choose between 1-3"

                      ;;

               esac

        done

 

        echo "what do you want to know?"

        select var in "location" "info" "package name"

        do

               case $var in

                location)

                       option=$option"l"

                       break

                      ;;

               info)

                       option=$option"i"

                       break

                      ;;

                package\ name)

                       break

                      ;;

               *)

                       echo "please choose between 1-3"

                      ;;

               esac

        done

 

        ${RPM}   $option $argument

 

        echo "continue? [yes/no]"

        read answer

 

        if [ answer = "no" ]

        then

               break

        fi

done

 

实训内容:编写一个Shell程序,呈现一个菜单,有0-5共6个命令选项,1为挂载U盘,2为卸载U盘,3为显示U盘的信息,4把硬盘中的文件拷贝到U盘,5把U盘中的文件拷贝到硬盘中,选0为退出。

程序分析:把此程序分成题目中要求的6大功能模块,另外加一个菜单显示及选择的主模板。

(1)       编辑代码

 [root@localhost  bin]#vi test19

#!/bin/sh

#mountusb.sh

#退出程序函数

quit()

{

  clear

  echo “*******************************************************************”

  echo  “***           thank you to use,Good bye!            ****”

  exit 0

  }

 #加载U盘函数

 mountusb()

 {

  clear

  #在/mnt下创建usb目录

  mkdir /mnt/usb

  #查看U盘设备名称

  /sbin/fdisk –l |grep /dev/sd

  echo –e “Please Enter the device name of usb as shown above:\c”

read PARAMETER

mount /dev/$PARAMETER /mnt/usb

}

#卸载U盘函数

umountusb()

{

  clear

  ls -la /mnt/usb

}

#显示U盘信息函数

display()

{

  clear

  umount /mnt/usb

}

#拷贝硬盘文件到U盘函数

cpdisktousb()

{

   clear

   echo –e “Please Enter the filename to be Copide (under Current directory):\c”

   read FILE

   echo “Copying,please wait!...”

   cp $FILE /mnt/usb

}

#拷贝U盘函数到硬盘文件

cpusbtodisk()

{

  clear

  echo -e “Please Enter the filename to be Copide in USB:\c”

  read FILE

  echo “Copying ,Please wait!...”

  cp /mnt/usb/$FILE .  #点(.)表示当前路径

}

  clear

  while true

  do

echo “=====================================================================”

echo “***           LINUX USB MANAGE PROGRAM                     ***”

echo  “              1-MOUNT USB                                    ”

echo  “              2-UNMOUNT USB                                  ”

echo  “              3-DISPLAY USB INFORMATION                      ”

echo  “              4-COPY FILE IN DISK TO USB                     ”

echo  “              5-COPY FILE IN USB TO DISK                     ”

echo  “              0-EXIT                                         ”

echo “=====================================================================”

echo –e “Please Enter a Choice(0-5):\c”

read CHOICE

case $CHOICE in

1)  mountusb

2)  unmountusb

3)  display

4)  cpdisktousb

5)  cpusbtodisk

0)  quit

*)  echo “Invalid Choice!Corrent Choice is (0-5)”

    sleep 4

    clear;;

 esac

done

(2)修改权限

[root@localhost  bin]#chmod +x test19

(3)程序执行结果

[root@localhost  bin]#./ test19

 

 


热点排行