linux腳本編程-函數建立

1.函數的基本格式node

function name {
   commands
}

//或者
name(){

}

2.使用函數shell

#!/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 $?

函數returnbash

#!/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會將本身加到本身上面生成結果this

全局變量:code

#!/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

函數庫建立three

#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
}

庫的引用(庫引用在前面加上兩個點好)ip

#!/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[@]}
相關文章
相關標籤/搜索