shell函数使用方法

前端之家收集整理的这篇文章主要介绍了shell函数使用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

!/bin/bash

  1. #函数示例
  2. function func1 {
  3. echo "This is an example of a function"
  4. }
  5.  
  6. count=1
  7. while [ $count -le 5 ]
  8. do
  9. func1
  10. count=$[$count + 1 ]
  11. echo "count:" $count
  12. done
  13.  
  14. echo "This is the end of the loop"
  15.  
  16. func1
  17.  
  18. echo "Now this is the end of the script"
  1. #获取函数返回值
  2. function db1 {
  3. #read -p "Enter a value: " value
  4. value=3
  5. echo $[ $value * 2 ]
  6. }
  7. result=$(db1)
  8. echo "The new value is $result"
  1. #向函数传递参数
  2. function addem {
  3. if [ $# -eq 0 ] || [ $# -gt 2 ]
  4. then
  5. echo -1
  6. elif [ $# -eq 1 ]
  7. then
  8. echo $[ $1 + $1 ]
  9. else
  10. echo $[ $1 + $2 ]
  11. fi
  12. }
  13. echo -n "Adding 10 and 15:"
  14. value=$(addem 10 15)
  15. echo $value
  1. #通过脚本直接传递参数,函数也使用了$1和$2变量,但它们和脚本主体中的$1和$2变量并不相同。要在函数
  2. #使用这些值,必须在调用函数时手动将它们传过去
  3.  
  4. function badfunc1 {
  5. echo $[ $1 * $2 ]
  6. }
  7.  
  8. if [ $# -eq 2 ]
  9. then
  10. value=$(badfunc1 $1 $2)
  11. echo "The result is $value"
  12. else
  13. echo "Usage: badtest1 a b"
  14. fi
  1. #shell脚本局部变量
  2. function func1 {
  3. local temp=$[ $value + 5 ]
  4. echo "The local temp is $temp"
  5. result=$[ $temp *2 ]
  6. }
  7.  
  8. temp=4
  9. value=6
  10.  
  11. func1
  12. echo "The result is $result"
  13. echo "The global temp is $temp"
  14.  
  15. if [ $temp -gt $value ]
  16. then
  17. echo "temp is larger"
  18. else
  19. echo "temp is smaller"
  20. fi
  1. #向脚本中传入数组,此种方法只能传一个参数
  2. function testit {
  3. echo "The parameters are: $@"
  4. thisarray=$1
  5. echo "The received array is ${thisarray[*]}"
  6.  
  7. }
  8.  
  9. myarray=(1 2 3 4 5)
  10. echo "Ther original array is:${myarray[*]}"
  11. testit $myarray
  1. #向脚本中传入数组的正确写法
  2. function testit {
  3. echo "number:$#"
  4. echo "argume:$@"
  5. local newarray
  6. newarray=(`echo "$@"`)
  7. echo "The new array value is: ${newarray[*]}"
  8. }
  9.  
  10. myarray=(1 2 3 4 5)
  11. echo "The original array is ${myarray[*]}"
  12. testit ${myarray[*]}
  1. #使用数组变量
  2. function addarray {
  3. local sum=0
  4. local newarray
  5. newarray=($(echo "$@"))
  6. for value in ${newarray[*]}
  7. do
  8. sum=$[ $sum + $value ]
  9. done
  10. echo $sum
  11. }
  12.  
  13. myarray=(1 2 3 4 5)
  14. echo "The original array is:${myarray[*]}"
  15. arg1=$(echo ${myarray[*]})
  16. result=$(addarray ${myarray[*]})
  17. echo "The result is $result"
  18. echo "------------------------------"
  19. result=$(addarray $arg1)
  20. echo "The result is $result"

猜你在找的Bash相关文章