050-調用函數與函數返回值

 1.調用函數肯定文件是否存在

[root@cnsz142728 scripts]# vim checkfileexist.sh 
#!/bin/bash
FILE=/etc/notexistfile
function checkfileexist() {
   if [ -f $FILE ];then
      return 0
   else
      return 1
   fi
}
echo "This test will let you know whether $FILE is exists. "
checkfileexist
   if [ $? -eq 0 ];then
    echo "$FILE exist"
   else
    echo "$FILE is not exist"
   fi

"checkfileexist.sh" 17L, 302C written                                                                                                                                                                                     
[root@cnsz142728 scripts]# ./checkfileexist.sh  
This test will let you know whether /etc/notexistfile is exists. 
/etc/notexistfile is not exist

該腳本中的調用函數是checkfileexist(),以後輸入checkfileexist就是調用該函數vim

2.函數返回值

[root@cnsz142728 scripts]# vim number.sh
#!/bin/bash

function test(){

read -p "Please input number:" num
#read num
         if [ $num -ge 0 -a $num -lt 10 ];then
             return 0
          fi
         if [ $num -ge 10 -a $num -lt 20 ];then
             return 1
         fi
         if [ $num -ge 20 -a $num  -lt 30 ];then
             return 2
         fi
             return 3
}
echo "Start calling function"
test
park=$?
       if [ $park -eq 0 ];then
         echo "The number is between [0,10)"
       
         elif [ $park -eq 1 ];then
         echo "The number is between [10,20)"
         elif [ $park -eq 2 ];then
         echo "The number is between [20,30)"
       else
         echo " unknown number"
fi

"number.sh" 31L, 702C written                                                                                                                                                                                             
[root@cnsz142728 scripts]# ./number.sh 
Start calling function
Please input number:2
The number is between [0,10)
[root@cnsz142728 scripts]# ./number.sh 
Start calling function
Please input number:44
 unknown number
[root@cnsz142728 scripts]# ./number.sh 
Start calling function
Please input number:22
The number is between [20,30)
[root@cnsz142728 scripts]# ./number.sh 
Start calling function
Please input number:15
The number is between [10,20)
[root@cnsz142728 scripts]#

該腳本運用if 語句,if elif ..else以及調用函數和返回值bash

3.functions函數庫,該函數庫總共有27個函數函數

[root@cnsz142728 September]# vim functions.sh 
#/bin/bash
. /etc/init.d/functions
confirm ITEM

if [[ $? -le 0 ]];then
   echo "ITEM confirmed"
else
  echo "ITEM is not comfirmed"
fi
 
"functions.sh" 9L, 137C written                                                                                                                                                                                           
[root@cnsz142728 September]# ./functions.sh 
Start service ITEM (Y)es/(N)o/(C)ontinue? [Y] Y
ITEM confirmed
[root@cnsz142728 September]# ./functions.sh 
Start service ITEM (Y)es/(N)o/(C)ontinue? [Y] N
ITEM is not comfirmed
相關文章
相關標籤/搜索