1、在Shell中定义的变量默认是全局变量,要想让变量的作用域仅限于函数内部,在内部定义时加上local标识。
计算下列所有人的总票价:
男士票价:100 元1人 女士票价:80元1人 儿童票价:50元1人
总共有5位男士,5位女士, 10位儿童
#!/bin/bin
MAN_TICKET=100
WOMAN_TICKET=80
CHILD_TICKET=50
TOTAL_PRICE=0
function ticket() {
if [ -n $1 ]; then
if [ $1 == "man" ]; then
COUNT=0
while [ $COUNT -lt $2 ]
do
let TOTAL_PRICE+=$MAN_TICKET
let COUNT++
done
elif [ $1 == "women" ]; then
COUNT=0
while [ $COUNT -lt $2 ]
do
let TOTAL_PRICE+=$WOMAN_TICKET
let COUNT++
done
elif [ $1 == "child" ]; then
COUNT=0
while [ $COUNT -lt $2 ]
do
let TOTAL_PRICE+=$CHILD_TICKET
let COUNT++
done
fi
else
echo "param $1 is not man or women or child"
fi
}
ticket man 5
echo "totol ticket is $TOTAL_PRICE"
ticket women 5
ticket child 10
echo "total ticket is $TOTAL_PRICE"
totol ticket is 500
total ticket is 1400