shell函数使用方法

!/bin/bash

#函数示例
function func1 {
   echo "This is an example of a function"
}

count=1
while [ $count -le 5 ]
do 
   func1
   count=$[$count + 1 ]
   echo "count:" $count
done 

echo "This is the end of the loop"

func1

echo "Now this is the end of the script"
#获取函数返回值
function db1 {
  #read -p "Enter a value: " value
  value=3
  echo $[ $value * 2 ]
}
result=$(db1)
echo "The new value is $result"
#向函数传递参数
function addem {
  if [ $# -eq 0 ] || [ $# -gt 2 ]
  then
     echo -1
  elif [ $# -eq 1 ]
  then
     echo $[ $1 + $1 ]
  else
     echo $[ $1 + $2 ]
  fi
}
echo -n "Adding 10 and 15:"
value=$(addem 10 15)
echo $value
#通过脚本直接传递参数,函数也使用了$1和$2变量,但它们和脚本主体中的$1和$2变量并不相同。要在函数中
#使用这些值,必须在调用函数时手动将它们传过去

function badfunc1 {
  echo $[ $1 * $2 ]
}

if [ $# -eq 2 ]
then 
  value=$(badfunc1 $1 $2)
  echo "The result is $value"
else
  echo "Usage: badtest1 a b"
fi  
#shell脚本局部变量
function func1 {
   local temp=$[ $value + 5 ]
   echo "The local temp is $temp"
   result=$[ $temp *2 ]
}

temp=4
value=6

func1
echo "The result is $result"
echo "The global temp is $temp"

if [ $temp -gt $value ]
then
   echo "temp is larger"
else 
   echo "temp is smaller"
fi
#向脚本中传入数组,此种方法只能传一个参数
function testit {
  echo "The parameters are: $@"
  thisarray=$1
  echo "The received array is ${thisarray[*]}"

}

myarray=(1 2 3 4 5)
echo "Ther original array is:${myarray[*]}"
testit $myarray
#向脚本中传入数组的正确写法
function testit {
   echo "number:$#"
   echo "argume:$@"
   local newarray
   newarray=(`echo "$@"`)
   echo "The new array value is: ${newarray[*]}"
}

myarray=(1 2 3 4 5)
echo "The original array is ${myarray[*]}"
testit ${myarray[*]}
#使用数组变量
function addarray {
   local sum=0
   local newarray
   newarray=($(echo "$@"))
   for value in ${newarray[*]}
   do
      sum=$[ $sum + $value ]
   done 
   echo $sum
}

myarray=(1 2 3 4 5)
echo "The original array is:${myarray[*]}"
arg1=$(echo ${myarray[*]})
result=$(addarray ${myarray[*]})
echo "The result is $result"
echo "------------------------------"
result=$(addarray $arg1)
echo "The result is $result"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值