zoukankan      html  css  js  c++  java
  • centos shell脚本编程2 if 判断 case判断 shell脚本中的循环 for while shell中的函数 break continue test 命令 第三十六节课

    centos  shell脚本编程2 if 判断  case判断   shell脚本中的循环  for   while   shell中的函数  break  continue  test 命令   第三十六节课

    return用在函数中
    exit用在shell当中 直接退出整个脚本,整个子shell或当前shell
    break退出循环

    上半节课

    if 判断
    case判断
    shell脚本中的循环

    下半节课

    for
    while
    shell中的函数
    break
    continue

    课程大纲(继续上节课的)

    7. if 判断一些特殊用法
    if [ -z $a ] 这个表示当变量a的值为空时会怎么样 if [ -z $a ];then ehco "$a is null" ok; fi
    if grep -q '123' 1.txt; then 表示如果1.txt中含有'123'的行时会怎么样
    if [ ! -e file ]; then 表示文件不存在时会怎么样
    if (($a<1)); then …等同于 if [ $a -lt 1 ]; then… [ ] 中不能使用<,>,==,!=,>=,<=这样的符号


    8. shell中的case判断
    格式: case 变量名 in
    value1)  #匹配value1
    command
    ;;
    value2)  #匹配value2
    command
    ;;
    *)   #表示匹配任何东西,可以用来检测非法输入
    commond
    ;;
    esac

    在case程序中,可以在条件中使用|,表示或的意思, 比如
    2|3)
    command
    ;;

    当变量为2或者3时,执行该部分命令。
    注意:case语句里面不能写判断 case xx in >80 ;; >60 是不能的

    案例:

    #!/bin/bash
    read -p "Please input a number: " n
    
    if [ -z $n ]
    then
    echo "Please input a number."
    exit 1
    fi
    
    n1=`echo $n|sed 's/[-0-9]//g'`
    
    if [ ! -z $n1 ]
    then
    echo "Please input a number."
    exit 1
    #elif [ $n -lt 0 ] || [ $n -gt 100 ]
    #then
    # echo "The number range is 0-100."
    # exit 1
    fi
    
    if [ $n -lt 60 ]
    then
    tag=1
    elif [ $n -ge 60 ] && [ $n -lt 80 ]
    then
    tag=2
    elif [ $n -ge 80 ] && [ $n -lt 90 ]
    then
    tag=3
    elif [ $n -ge 90 ] && [ $n -le 100 ]
    then
    tag=4
    else
    tag=0
    fi
    
    
    
    case $tag in
    1)
    echo "不及格"
    ;;
    2)
    echo "及格"
    ;;
    3|4)
    echo "优秀"
    ;;
    *)  #匹配任何东西,检测非法输入
    echo "The number range is 0-100."
    ;;
    esac
    
    不能写在 1) 前面
    *)
    echo "The number range is 0-100."
    ;;

    9. shell脚本中的循环
    seq命令
    默认从1开始
    seq 1 20 等价于 seq 20
    seq -1 -20
    seq 10 -1 1 倒数 -1为步长
    for循环 语法结构: for 变量名 in 条件; do … done

    案例1:

    #!/bin/bash
    sum=0
    for i in `seq 1 100`
    do
    sum=$[$sum+$i]
    echo $i
    done
    echo $sum

    案例2:
    注意:ls跟find不一样,find会显示绝对路径,ls不会,所以要加/etc/$a,或者在脚本开头加cd /etc/

    #!/bin/bash
    cd /etc/
    for a in `ls /etc/`
    do
    
    if [ -d /etc/$a ]
    then
    ls -d /etc/$a
    fi
    done

    结果
    # sh for.sh
    /etc/abrt
    /etc/acpi
    /etc/alsa
    /etc/alternatives
    /etc/audisp
    /etc/audit
    。。。


    案例3:
    循环打印一个文本文件,默认以空格为换行符,不是回车,所以还需要用sed处理,不能用cat

    #!/bin/bash
    n=`wc -l 1.txt |awk '{print $1}'`
    for i in `seq 1 $n`
    do
    sed -n "$i"p 1.txt
    done

    while 循环语法结构: while 条件; do … done 死循环用:表示
    案例1:

    #!/bin/bash
    while :
    do
    load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d. -f1`
    if [ $load -gt 10 ]
    then
    top -bn 1|mail -s "load is high: $load" asldkfls@11.com
    fi
    sleep 30
    done

    案例2:

    #!/bin/bash
    
    while :
    do
    read -p "Please input a number: " n
    if [ -z $n ]
    then
    echo "你需要输入东西"
    continue
    fi
    
    n1=`echo $n|sed 's/[-0-9]//g'`
    
    if [ ! -z $n1 ]
    then
    echo "你只能输入一个纯数字"
    continue
    fi
    break
    done
    echo $n


    break直接结束本层循环;

    #!/bin/bash
    for i in `seq 1 5`
    do
    echo $i
    if [ $i == 3 ]
    then
    break
    fi
    echo $i
    done
    echo aaaaaaa

    continue忽略continue之下的代码,直接进行下一次循环

    #!/bin/bash
    for i in `seq 1 5`
    do
    echo $i
    if [ $i == 3 ]
    then
    continue
    fi
    echo $i
    done
    echo $i

    exit 直接退出shell

    #!/bin/bash
    for i in `seq 1 5`
    do
    echo $i
    if [ $i == 3 ]
    then
    exit
    fi
    echo $i
    done
    echo aaaaaaa

    10. shell中的函数
    函数就是把一段代码整理到了一个小单元中,并给这个小单元起一个名字,当用到这段代码时直接调用这个小单元的名字即可。
    格式: function f_name() {
    command
    }
    函数必须要放在最前面

    函数调用函数,被调用函数需要先在函数前定义

    注意:命令和花括号之间要有空格

    ping_fun(){
    echo 1}
    正确应该是
    ping_fun(){
    echo 1
    }
    或者
    ping_fun(){
    echo 1 }

    案例1:

    #!/bin/bash
    input() {
    echo $1
    }

    案例2:

    #!/bin/bash
    sum() {
    s=$[$1+$2]
    echo $s #或者return $s
    }
    
    sum 1 2

    echo $?
    3


    案例3:

    #!/bin/bash
    ip() {
    ifconfig |grep -A1 "$1 " |grep addr |awk '{print $2}'|awk -F':' '{print $2}'
    }
    
    read -p "Please input the eth name: " e
    myip=`ip $e`
    echo "$e address is $myip"

    函数里可以export 全局变量

    案例4:

    猜数字游戏
    $RANDOM 生成随机数
    
    $[$RANDOM%100] 100之内的随机数  取余
    
    #!/bin/bash
    n=$[$RANDOM%100]
    while :
    do
    read -p "pleas input a number:" n1
    n2=`echo $n1 |sed 's/[0-9]//g'`
    if [ ! -z $n2 ]
    then
        echo "your number is not a number"
        continue
    fi
    if [ $n1 == $n ]
    then
        echo "right"
        echo $n
    elif [ $n1 -gt $n ]
    then    
        echo "bigger"
        continue
    else
        echo "smaller"
        continue
    fi
    done

    案例5:

    #ping函数
    #!/bin/bash #write by 2016-2-2 ping_fun(){ if ping -c $1 $2 > /dev/null 2>&1 then return 0 else return 1 fi } host=192.168.12.253 count=2 while : do ping_fun $count $host if [ $? -eq 0 ] then echo "$host is up" else echo "$host is down " |mail -s "$host is down " abc@139.com fi sleep 3 done


    11. shell练习题
    编写shell脚本,计算1-100的和;
    编写shell脚本,要求输入一个数字,然后计算出从1到输入数字的和,要求,如果输入的数字小于1,则重新输入,直到输入正确的数字为止;
    编写shell脚本,把/root/目录下的所有目录(只需要一级)拷贝到/tmp/目录下;
    编写shell脚本,批量建立用户user_00, user_01, ... user_100并且所有用户同属于users组;
    编写shell脚本,截取文件test.log中包含关键词 ‘abc’ 的行中的第一列(假设分隔符为 ”:” ),然后把截取的数字排序(假设第一列为数字),然后打印出重复次数超过10次的列;

    扩展学习:
    select用法 http://www.apelearn.com/bbs/thread-7950-1-1.html


    扩展阅读

    shell中的select用法 [复制链接]
    select也是循环的一种,它比较适合用在用户选择的情况下。
    比如,我们有一个这样的需求,运行脚本后,让用户去选择数字,选择1,会运行w命令,选择2运行top命令,选择3运行free命令,选择4退出。输入序号1、2、3、4

    脚本这样实现:

    #!/bin/bash
    echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
    echo
    select command in w top free quit  #从数字1开始 只能输入数字  1w 2top 3free 4quit
    do
    case $command in
    w)
    w
    ;;
    top)
    top
    ;;
    free)
    free
    ;;
    quit)
    exit
    ;;
    *)
    echo "Please input a number:(1-4)."
    ;;
    esac
    done

    执行结果如下:
    sh select.sh
    Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit

    1) w
    2) top
    3) free
    4) quit
    #? 1
    16:03:40 up 32 days, 2:42, 1 user, load average: 0.01, 0.08, 0.08
    USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
    root pts/0 61.135.172.68 15:33 0.00s 0.02s 0.00s sh select.sh

    #? 3
    total used free shared buffers cached
    Mem: 1020328 943736 76592 0 86840 263624
    -/+ buffers/cache: 593272 427056
    Swap: 2097144 44196 2052948
    #?


    我们发现,select会默认把序号对应的命令列出来,每次输入一个数字,则会执行相应的命令,命令执行完后并不会退出脚本。它还会继续让我们再次输如序号。序号前面的提示符,我们也是可以修改的,利用变量PS3即可,再次修改脚本如下:

    #!/bin/bash
    PS3="Please select a number: "
    echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
    echo
    
    select command in w top free quit
    do
    case $command in
    w)
    w
    ;;
    top)
    top
    ;;
    free)
    free
    ;;
    quit)
    exit
    ;;
    *)
    echo "Please input a number:(1-4)."
    esac
    done


    如果想要脚本每次输入一个序号后就自动退出,则需要再次更改脚本如下:

    #!/bin/bash
    PS3="Please select a number: "
    echo "Please chose a number, 1: run w, 2: run top, 3: run free, 4: quit"
    echo   #换行
    
    select command in w top free quit
    do
    case $command in
    w)
    w;exit
    ;;
    top)
    top;exit
    ;;
    free)
    free;exit
    ;;
    quit)
    exit
    ;;
    *)
    echo "Please input a number:(1-4).";exit
    esac
    done

    echo换行

    实际上是echo 一个空行

    echo 相当于 echo ' '

    cat bb.sh

    #!/bin/bash
    echo 'sf'
    echo
    echo 'ii'

    sh bb.sh
    sf

    ii


    test 命令用法详解
    --http://blog.csdn.net/duguteng/article/details/7725845

    基本格式:
    test expression
    expression为test命令构造的表达式。
    这里expression是test命令可以理解的任何有效表达式,该简化格式将是读者可能会踫见的最常用格式
    返回值:
    test命令或者返回0(真) 或者返回1(假).

    方式:
    表达式判断
    字符串比较
    数字比较
    文件比较

    也就是说
        test option file
    可以全部改写成:
        [ option file ]
    例如:
     test –w File
    改写成    
    [ –w File ]

       
    【示例】
    //判断第一个参数是否为空字符串,不空则打印
    if test -n "$1"
    then
    echo "$1"
    fi
    测试,放到文件当中
    #!/bin/sh
    if test -n "$1"
    then
    echo "$1"
    fi
    执行
    chmod +x test.sh
    ./test.sh www.linuxpig.com

    if  test  $? -eq 0

    判断返回值是否等于0



    shell中自带的正则匹配
    http://bbs.chinaunix.net/thread-4125147-1-1.html
    if [[ ! "$arch" =~ x86 ]];then
        echo "$2" > /etc/setup/last-mirror
        echo "" > /etc/setup/last-arch




    例子
    <List>
        <Job id="1" name="abc"/>
        <Job id="2" name="zyz"/>
        <Job id="3" name="beew"/>
    </List>

    想要得到这个结果。
    abc | 1
    zyz | 2
    beew | 3


    #!/bin/bash

    while read  line; do
      if [[ $line =~ id="([0-9]+).*name="([^"]*) ]]; then
        echo "${BASH_REMATCH[2]} | ${BASH_REMATCH[1]}"
      fi
    done < file

    如果你对sed 里的 1 2 的用法很熟的话,就应该很快的明白 BASH_REMATCH[1] 和 BASH_REMATCH[2] 代表了什么。

    f

  • 相关阅读:
    java架构之路-(nginx使用详解)nginx的反向代理和优化配置
    java架构之路-(nginx使用详解)nginx的安装和基本配置
    java架构之路-(mysql底层原理)Mysql之让我们再深撸一次mysql
    java架构之路(mysql底层原理)Mysql之Explain使用详解
    java架构之路-(mysql底层原理)Mysql索引和查询引擎
    java架构之路(多线程)JMM和volatile关键字
    算法初步---基本的数据结构(java为例)
    python基础之Matplotlib库的使用一(平面图)
    使用NumPy、Numba的简单使用(二)
    使用NumPy、Numba的简单使用(一)
  • 原文地址:https://www.cnblogs.com/MYSQLZOUQI/p/5153596.html
Copyright © 2011-2022 走看看