bash shell基础

1. 数组变量和函数

1.1 数组变量

注意:不能将数组变量作为函数函数参数,否则函数只会取数组变量的第一个值
例如:arry=(1 2 3 4 5); func ${arry}

1.2 函数

1.2.1函数库

[root@shell_test function]# cat oper.sh 
#!/bin/bash
#定义函数
function add {
  echo $[$1+$2]
}

function subtract {
  echo $[$1-$2]
}

function mult {
  echo $[$1*$2]
}
function divid {
  result=$(echo "scale=3;$1/$2"|bc)
  echo $result
}

[root@shell_test function]# cat main.sh 
#!/bin/bash
if [ $# -eq 2 ];
then
  . ./oper.sh
#  function test_zero {
#  #检测除数不能为0
#    if [ $2 -eq 0 ];then
#    
#    fi
#  }
  PS3="please input the option: "
  select option in "add" "subtract" "mult" "divid" "exit program"
  do
    case $option in 
    "add")
         clear
         echo "this is add operation..."
         result1=$(add $1 $2)
         echo "Result: ""$1+$2="$result1
    ;;
    "subtract")
         clear
         echo "this is subtract operation..."
         result2=`subtract $1 $2`
         echo "Result: ""$1-$2="$result2
    ;;
    "mult")
         clear
         echo "this is mult operation..."
         result3=`mult $1 $2`
         echo "Result: ""$1*$2="$result3
    ;;
    "divid")
         clear
         echo "this is divid operation..."
         if ! [ $2 -eq 0 ];then
           result4=$(divid $1 $2)
           echo "Result: ""$1/$2="$result4
         else
           echo "the para should't is zero!!!"
         fi
    ;;
    "exit program")
         break ;;
    *)
         clear
         echo "sorry,wrong selection..."
    ;;
    esac  
  done
else
  clear
  echo "Insufficient parameters!!!"
  sleep 2
  exit
fi
#执行脚本
this is divid operation...
Result: 444/555=.800
please input the option: 
1) add		 3) mult	  5) exit program
2) subtract	 4) divid
please input the option: 
1) add		 3) mult	  5) exit program
2) subtract	 4) divid
please input the option:
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值