Linux shell中的函数定义、传参和调用:
函数定义语法:
[ function ] functionName [()] {
}
示例:
#!/bin/bash# get limit
if [ $# -eq 1 ] && [ $1 -gt 0 ]; thenlimit=$1echo -e "\nINFO: input limit is $limit"
elselimit=-1echo -e "\nWARN: input limit for initDynamic is null!"
fihost_arr=()init(){host_arr[${#host_arr[@]}]=192.168.1.120host_arr[${#host_arr[@]}]=192.168.1.121host_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[@]}; doecho $idoneecho -e "\n------ show mode 3 -----"max=${#host_arr[@]}for ((i=0;i<$max;i++)); doecho ${host_arr[$i]};done
}function initDynamic () {for ((i=0,j=0;i<$1;i++)); doj=$(expr 120 + $i)host_arr[${#host_arr[@]}]=192.168.1.$jdone
}echo -e "\ninit result: "
reset
init
showResultecho -e "\ninitDynamic $limit result: "
reset
initDynamic $limit
showResultecho ""
执行结果如下: