zoukankan      html  css  js  c++  java
  • Shell 编程(函数)

    声明函数

    demoFun(){
        echo "这是我的第一个 shell 函数!"
    }

    函数名(){

      ...函数体

    }

     在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数...

    funWithParam(){
        echo "第一个参数为 $1 !"
        echo "第二个参数为 $2 !"
        echo "第十个参数为 $10 !"
        echo "第十个参数为 ${10} !"
        echo "第十一个参数为 ${11} !"
        echo "参数总数有 $# 个!"
        echo "作为一个字符串输出所有参数 $* !"
    }

    函数调用

     函数名 参数1 参数2

    eg:输入一个IP地址最后一位起、始,自动找到该网段内有哪些主机地址在线

    #!/bin/bash
    #
    CheckOnline() {
            ADDR=$1
            if ping -c 1 $ADDR &> /dev/null
            then
                    return 0
            else
                    return 1
            fi
    }
    if [ "$1" -gt 0 -a "$2" -gt 0 -a "$1" -lt "$2" ] 2>/dev/null
    then
            for((i=$1;i<$2;i++))
            do
                    if CheckOnline 192.168.1.$i
                    then
                            echo "192.168.1.$i is online"
                    fi
            done
    else
            echo "参数不正确"
    fi

    总结

      判断变量是否为数值型的方法

    ## 方法1
    #if [ "$1" -gt 0 ] 2>/dev/null ;then 
    #  echo "$1 is number." 
    #else 
    #  echo 'no.' 
    #fi 
        
    ## 方法2,case 
    #case "$1" in 
    #  [1-9][0-9]*)  
    #    echo "$1 is number." 
    #    ;; 
    #  *)  
    #    ;; 
    #esac 
    
     ## 方法3,expr 
    expr $1 "+" 10 &> /dev/null
    if [ $? -eq 0 ];then
      echo "$1 is number"
    else
      echo "$1 not number"
    fi
  • 相关阅读:
    call()与apply()的作用与区别
    Tomcat8/9的catalina.out中文乱码问题解决
    怎样查看Jenkins的版本
    每日日报2020.8.18
    528. Random Pick with Weight
    875. Koko Eating Bananas
    721. Accounts Merge
    515. Find Largest Value in Each Tree Row
    286. Walls and Gates (Solution 1)
    408. Valid Word Abbreviation
  • 原文地址:https://www.cnblogs.com/xiaoliwang/p/9028204.html
Copyright © 2011-2022 走看看