shell腳本之四:shift位置參數左移、函數、退出循環


1、Shift位置參數左移指令

1.1、定義:

 shift命令用於對位置參數的移動(左移),通常用於在不知道傳入參數個數的情況下依次遍歷每個參數然后進行相應處理。

1.2、作用:

     每執行一次,位置參數序列順次左移一個位置,$#的值減1,用於分別處理每個參數,移出去的參數,不再可用,例如執行一次shift位置參數就左移一次,原來的第一個位置參數被移出去了,不再可用,第二個位置參數成了第一個位置參數,依次類推。

 

1.3、實例:加法計算器

 [root@localhost ~]# cat shift.sh

 #!/bin/bash

 if [ $# -le 0 ];then

  echo "沒有提供足夠的參數"

  exit 1

 fi

 sum=0

 while [ $# -gt 0 ];do

  sum=$[$sum+$1]

  shift

 done

 echo “result is $sum”

 [root@localhost ~]# sh shift.sh

 沒有提供足夠的參數

 result is 0

 [root@localhost ~]# sh shift.sh 2 3 8 10

 result is 23

 [root@localhost ~]# sh shift.sh 2 3 8 -10 5

 result is 8

 [root@localhost ~]# cat shift.sh

 #!/bin/bash

 if [ $# -le 0 ];then

  echo "沒有提供足夠的參數"

  exit 1

 fi

 sum=0

 while [ $# -gt 0 ];do

  #sum=$[$sum+$1]

  sum=$(expr $sum + $1)

  #shift 2 一次移動2個參數

  shift

 done

 echo result is $sum

2、函數的使用

 函數是一個腳本代碼塊,你可以對它進行自定義命名,並且可以在腳本中任意位置使用這個函數,要使用這個函數,只要使用這個函數名稱就可以了

 函數:把一個功能封裝起來。使用時直接調用函數名。這樣的腳本好處:模塊化,代碼可讀性強。

2.1、函數創建

 兩種·創建函數的方法:

 方法一:

 function name() {

            命令序列

      [return value]

 }

 方法二:

 name() {

            命令序列

      [return value]

 }

 注意:

 1、其中function是可選的,這個可以省略掉。name是函數唯一的名稱,函數名后面加一個(),里面是沒有內容的。而我們執行的命令序列放在{}里面的,由{ }包圍的部分稱為函數體,調用一個函數,實際上就是執行函數體中的代碼。return value表示函數的返回值,其中 return 是 Shell 關鍵字,專門用在函數中返回一個值;這一部分可以寫也可以不寫。

 2、在定義函數的時候,必須要在執行程序前面定義或加載(即必須在調用函數地方之前,定義好函數)

 3、在執行函數時(調用函數),函數前面的function和函數后面的小括號都不要寫,直接寫函數名就可以了

2.2、函數的使用

 2.2.1、創建一個函數

 [root@localhost ~]# cat fun-1.sh

 #!/bin/bash

 # using a function in a script

  

 function func1() {              #定義函數

    echo "This is an example of a function"

 }

  

 count=1

 while [ $count -le 5 ]

 do

 func1                       #調用函數

 count=$[ $count + 1 ]

 done

  

 echo "This is the end of the while"

 func1                       #調用函數

 echo "Now this is the end of the script"

 [root@localhost ~]# sh fun-1.sh

 This is an example of a function

 This is an example of a function

 This is an example of a function

 This is an example of a function

 This is an example of a function

 This is the end of the while

 This is an example of a function

 Now this is the end of the script

2.2.2、函數返回值:函數的退出狀態

 默認情況下,函數的退出狀態是函數的最后一條命令返回的退出狀態。

 [root@localhost ~]# cat fun-2.sh

 #!/bin/bash

 # testing the exit status of a function

  

 func1() {

     echo "trying to display a non-existent file"

     ls -l badfile

 }

  

 echo "testing the function:"

 func1

 echo "The exit status is: $?"

 [root@localhost ~]# sh fun-2.sh

 testing the function:

 trying to display a non-existent file

 ls: cannot access badfile: No such file or directory

 The exit status is: 2

2.2.3、函數返回值:return命令返回特定的退出碼

 我們可以通過return命令來退出函數並返回特定的退出碼

 return命令可以使用單個整數值來定義函數退出狀態,提供了一種通過編程設置函數退出狀態的簡單方法。

 注:return語句返回一個退出值給調用函數的程序,而exit的返回值是給執行程序當前的SHELL

 [root@localhost ~]# cat fun-3.sh

 #!/bin/bash

 fun1(){

  ls badfile

  return 2

  echo "This is apple"

  return 5

 }

 fun1

 echo result is $?

 [root@localhost ~]# sh fun-3.sh

 ls: cannot access badfile: No such file or directory

 result is 2

在使用這個返回狀態碼的時候,要注意以下2點:

狀態碼必須要在函數一結束就進行取值。

 狀態碼的取值范圍(0~255)

2.3、把函數值賦給變量使用

 正如命令輸出可以捕獲並存放到 shell 變量中一樣,函數的輸出也可以捕獲並存放到 shell 變量中。

 范例1:

 [root@localhost ~]# cat fun-4.sh

 #!/bin/bash

 fun1(){

  read -p "Input a value: " VAR

  echo $[$VAR*5]

 }

  

 NUM=$(fun1)

 echo current num is $NUM

 [root@localhost ~]# sh fun-4.sh

 Input a value: 10

 current num is 50

2.4、向函數傳遞參數

2.4.1、 第一種情況

 函數可以使用位置參數變量來表示要傳遞給函數的參數。

 函數名在變量 $0 中定義, 函數命令行的其他參數使用變量 $1、$2..., $#可以用來確定傳遞給函數的參數數目。

 [root@localhost ~]# cat fun-5.sh

 #!/bin/bash

 function addem() {

     if [ $# -eq 0 ] || [ $# -gt 2 ]

     then

         echo "error,need to input one or two number."

     elif [ $# -eq 1 ]

     then

         echo $[ $1 + $1 ]

     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 number: "

 value=`addem 10`

 echo $value

  

 echo -n "Now trying adding no numbers: "

 value=`addem`

 echo $value

  

 echo -n "Finally, try adding three numbers: "

 value=`addem 10 15 20`

 echo $value

 執行腳本測試:

 [root@localhost ~]# sh fun-5.sh

 Adding 10 and 15: 25

 Let's try adding just one number: 20

 Now trying adding no numbers: error,need to input one or two number.

 Finally, try adding three numbers: error,need to input one or two number.

2.4.2、 第二種情況

 函數無法從腳本命令行(shell提示符中)直接訪問腳本參數值。如果想在函數中使用這些值,那么必須在調用該函數時手動傳遞這些數據。

 [root@localhost ~]# cat fun-6.sh

 #!/bin/bash

 # trying to access script parameters inside a function

  

 function func6 {

     echo $[ $1 * $2 ]

 }

  

 if [ $# -eq 2 ]

 then

     value=`func6 $1 $2`

     echo "The result is $value"

 else

     echo "Usage: badtest1 a b"

 fi

  [root@localhost ~]# sh fun-6.sh 4 6

 The result is 24

3、跳出循環

 在我們使用循環語句進行循環的過程中,有時候需要在未達到循環結束條件時強制跳出循環,那么Shell給我們提供了兩個命令來實現該功能:break和continue

 注:exit:退出當前整個腳本的

3.1、Break

 結束並跳出當前循環,在forwhile等循環語句中,用於跳出當前所在的循環體,執行循環體之后的語句,后面如果什么也不加,表示跳出當前循環等價於break 1,也可以在后面加數字,假設break 3表示跳出三層循環

范例1:

 [root@localhost ~]# cat break.sh

 #!/bin/bash

 while true

 do

  read -p "Enter a number [1-5]:" num

  case $num in

            1|2|3|4|5)

                              echo "GREATER"

                              ;;

                     *)

                              echo "wrong...Bye"

                              break

  esac

 done 

 [root@localhost ~]# sh break.sh

 Enter a number [1-5]:3

 GREATER

 Enter a number [1-5]:4

 GREATER

 Enter a number [1-5]:5

 GREATER

 Enter a number [1-5]:1

 GREATER

 Enter a number [1-5]:2

 GREATER

 Enter a number [1-5]:3

 GREATER

 Enter a number [1-5]:34

 wrong...Bye

3.2、Continue

 它和break命令差不多,忽略本次循環剩余的代碼,直接進行下一次循環;在forwhile等循環語句中,用於跳出當次循環,直接進入下一次循環。

范例2:

 [root@localhost ~]# cat continue.sh

 #!/bin/bash

 while true

 do

     echo -n "Input a number between 1 to 5: "

     read aNum

     case $aNum in

         1|2|3|4|5) echo "Your number is $aNum!"

         ;;

         *)

         echo "You do not select a number between 1 to 5!"

         continue

         echo "Game is over!"

         ;;

     esac

 done

范例3添加用戶的腳本

 [root@localhost ~]# cat add_user.sh

 #!/bin/bash

 while true

 do

   read -p "Please enter prefix & passwd & number: " pre pass num

   printf  "user information:

    ***********************

    user prefix:   $pre

    user password: $pass

    user number:   $num

   "

   read -p "Are you sure?[y/n] " action

   if [ "$action" == "y" ];then

      break

   fi

 done

 #adduser

 for i in $(seq -w $num)

 do

  user=${pre}${i}

  id $user &> /dev/null

  if [ $? -ne 0 ];then

    useradd $user

    echo "$pass"|passwd --stdin $user &> /dev/null

    if [ $? -eq 0 ];then

    echo -e "\e[31m$user\e[0m create"

    fi

  else

    echo "User $user exist"

  fi

 done

 執行腳本:

 

 刪除用戶:

 [root@localhost ~]# for i in `seq -w 1 11`;do userdel -r tech$i;done


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM