Shell总结07-函数Function

Shell总结07-函数Function

自定义函数及参数

##function 样式
# function FUNCTIONNAME { COMMANDS; } 
# or 
# FUNCTIONNAME () { COMMANDS; } 

test ()
{
echo "Positional parameter 1 in the function is $1."
RETURN_VALUE=$?
echo "The exit code of this function is $RETURN_VALUE."
}
test para1

##如果省略function关键字,必须有()
##function结束要有;或者另起新行
##通过FUNCTIONNAME来调用函数
##函数内部,通过“$n”的形式来获取参数的值,$1是第一个,$2是第二个...以此类推

示例

[root@nginx-node01 nginx]# cat checkinstall.sh      
#!/bin/bash
#auto install packages nginx required 

function checkInstall(){
  echo "Checking $1 installed or not"
  #rpm -q $1 >/dev/null 2>&1
  rpm -q $1 
  if [ $? -eq 0 ]; then
        echo "$1 installed "
  else
        echo "$1 not installed, will install $1 "
        yum -y install $1
        if [ $? -ne 0 ];then
          echo "Install $1" /bin/false
          exit 1
        fi
  fi
}

##环境及依赖检查
#gcc
checkInstall gcc-c++

猜你喜欢

转载自www.cnblogs.com/elfcafe/p/13171975.html
今日推荐