1.函数的基本格式
function name {
commands
}
//或者
name(){
}
2.使用函数
#!/bin/bash
#testing function
function func1 {
echo "This is a example if function"
}
count=1
while [ $count -lt 10 ]
do
echo $count
func1
count=$[ $count+1 ]
done
函数退出状态码
#!/bin/bash
#testing function exit status
func1() {
echo "Try to diplay a no exitent file"
}
func1
echo $?
函数return
#!/bin/bash
#using the return command in a function
function db1() {
return $[ 2*5 ]
}
a=`db1`
echo $a
3.向函数传递参数
#!/bin/bash
#passing parameters to a function
function addem {
if [ $# -eq 0 ] || [ $# -gt 2]
then
echo -1
elif [ $# -eq 1 ]
then
echo $[ $1+$2 ]
else
echo $[ $1+$2 ]
fi
}
echo -n "Adding 10 and 15:"
value=`addem 10 15`
echo $value
echo -n "Let's try adding just one numbers:"
value=`addem 10`
echo -n "Now trying adding no numbers:"
value=`addem`
echo $value
echo -n "Finaly, try adding three numbers:"
value=`addem 10 15 20`
没有参数是或者多余要求的参数,函数都会返回-1,如果只有一个参数,addem会将自己加到自己上面生成结果
全局变量:
#!/bin/bash
#using a global variable to pass a value
function db1 {
value=$[ $value*2 ];
}
read -p "Enter a value:" value
db1
echo "The new value is:$value"
数组变量和函数
#!/bin/bash
#trying to pass an array variable
function testit {
echo "The parameters are:$@"
thisarray=$1
echo "The recevied array is ${thisarray[*]}"
}
myarray=(1 2 3 4 5)
echo "The orginial array is :${myarray[*]}"
testit $myarray
函数库创建
#my script functions
function addem {
echo $[ $1+$2 ]
}
function multem {
echo $[ $1*$2 ]
}
function divem {
if [ $2 -ne 0 ]
then
echo $[ S1/$2 ]
else
echo -1
fi
}
库的引用(库引用在前面加上两个点好)
#!/bin/bash
#using functions defined in a library file
../myfuncs
value1=10
value2=5
result1=`addem $value $value2`
result2=`multem $value1 $value2`
result3=`divem $value1 $value2`
echo "The result of adding them is:$result1"
echo "The result of multiplying them is:$result2"
echo "The result of dividing them is:$result3"
递归获取文件
function getdir(){
echo $1
for file in $1/*
do
if test -f $file
then
echo $file
arr=(${arr[*]} $file)
else
getdir $file
fi
done
}
getdir /usr/local/recommend/config/
echo "INFO **************************"
echo ${arr[@]}
bar=$(IFS=, ; echo "${arr[*]}")
echo $bar
获取目录下的文件
for f in `ls`
do
if [[ $f == *.yaml ]]
then
//do something
fi
done
shell数组操作(数组切片)
#!/bin/bash
arr=(192.168.237.129 192.168.237.130 172.168.9.1 192.168.237.131)
a=3
echo ${arr[@]:0:a}
new_arr=(${arr[@]:0:a})
for ip in ${new_arr[*]}
do
echo $ip
done
shell读取文件到数组
#!/bin/bash
CUR_PATH=$(cd `dirname $0`;pwd)
echo "INFO: current excute path is ${CUR_PATH}"
file=${CUR_PATH}/node.conf
lines=$(cat $file)
for line in $lines; do
echo "$line"
arr=(${arr[*]} $line)
done
echo ${arr[@]}