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: