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
原文地址:https://www.cnblogs.com/xiaoliwang/p/9028204.html