溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何理解Shell函數(shù)參數(shù)

發(fā)布時間:2021-09-29 17:06:55 來源:億速云 閱讀:150 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“如何理解Shell函數(shù)參數(shù)”,在日常操作中,相信很多人在如何理解Shell函數(shù)參數(shù)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何理解Shell函數(shù)參數(shù)”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

在shell中,調(diào)用函數(shù)時可以向其傳遞參數(shù)。在函數(shù)體內(nèi)部,通過 $n 的形式來獲取參數(shù)的值,例如,$1表示第一個參數(shù),$2表示第二個參數(shù)...

帶參數(shù)的函數(shù)示例:

#!/bin/bash
funWithParam(){
  echo "The value of the first parameter is $1 !"
  echo "The value of the second parameter is $2 !"
  echo "The value of the tenth parameter is $10 !"
  echo "The value of the tenth parameter is ${10} !"
  echo "The value of the eleventh parameter is ${11} !"
  echo "The amount of the parameters is $# !"
  echo "The string of the parameters is $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

輸出:

The value of the first parameter is 1 !
The value of the second parameter is 2 !
The value of the tenth parameter is 10 !
The value of the tenth parameter is 34 !
The value of the eleventh parameter is 73 !
The amount of the parameters is 12 !
The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"

注意,$10 不能獲取第十個參數(shù),獲取第十個參數(shù)需要${10}。當n>=10時,需要使用${n}來獲取參數(shù)。

另外,還有幾個特殊字符用來處理參數(shù):

參數(shù)處理說明
$#傳遞到腳本的參數(shù)個數(shù)
$*以一個單字符串顯示所有向腳本傳遞的參數(shù)
$$腳本運行的當前進程ID號
$!后臺運行的最后一個進程的ID號
$@與$#相同,但是使用時加引號,并在引號中返回每個參數(shù)。
$-顯示Shell使用的當前選項,與set命令功能相同。
$?顯示最后命令的退出狀態(tài)。0表示沒有錯誤,其他任何值表明有錯誤。

到此,關于“如何理解Shell函數(shù)參數(shù)”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI