Linux shell中的函数定义、传参和调用
Linux shell中的函数定义、传参和调用:
函数定义语法:
[ function ] functionName [()] {
}
示例:
#!/bin/bash
# get limit
if [ $# -eq 1 ] && [ $1 -gt 0 ]; then
limit=$1
echo -e "\nINFO: input limit is $limit"
else
limit=-1
echo -e "\nWARN: input limit for initDynamic is null!"
fi
host_arr=()
init(){
host_arr[${#host_arr[@]}]=192.168.1.120
host_arr[${#host_arr[@]}]=192.168.1.121
host_arr[${#host_arr[@]}]=192.168.1.122
}
reset(){
host_arr=()
}
showResult(){
echo -e "------ show mode 1 -----"
echo "${host_arr[@]}"
echo -e "\n------ show mode 2 -----"
for i in ${host_arr[@]}; do
echo $i
done
echo -e "\n------ show mode 3 -----"
max=${#host_arr[@]}
for ((i=0;i<$max;i++)); do
echo ${host_arr[$i]};
done
}
function initDynamic () {
for ((i=0,j=0;i<$1;i++)); do
j=$(expr 120 + $i)
host_arr[${#host_arr[@]}]=192.168.1.$j
done
}
echo -e "\ninit result: "
reset
init
showResult
echo -e "\ninitDynamic $limit result: "
reset
initDynamic $limit
showResult
echo ""
执行结果如下: