shell學習之$@ 與 $* 差在哪?

來源:互聯網
上載者:User

標籤:shell

要說 [email protected] 與 $* 之前,需得先從 shell script 的 positional parameter 談起...
我們都已經知道變數(variable)是如何定義及替換的,這個不用再多講了。
但是,我們還需要知道有些變數是 shell 內定的,且其名稱是我們不能隨意修改的,
其中就有 positional parameter 在內。在 shell script 中,我們可用 $0, $1, $2, $3 ... 這樣的變數分別提取命令列中的參數,

如ls -l          ls為$0, -l為$1


首先是 $# :它可抓出 positional parameter 的數量。

以前面的 my.sh p1 "p2 p3" 為例:

由於 p2 與 p3 之間的 IFS 是在 soft quote 中,因此 $# 可得到 2 的值


接下來就是 [email protected] 與 $* :
精確來講,兩者只有在 soft quote 中才有差異,否則,都表示"全部參數"( $0 除外)。
舉例來說好了:若在 command line 上跑 my.sh p1 "p2 p3" p4 的話,
不管是 [email protected] 還是 $* ,都可得到 p1 p2 p3 p4 就是了。
但是,如果置於 soft quote 中的話:
"[email protected]" 則可得到 "p1" "p2 p3" "p4" 這三個不同的詞段(word);
"$*" 則可得到 "p1 p2 p3 p4" 這一整串單一的詞段。


我們可修改一下前面的 my.sh ,使之內容如下:
代碼:
#!/bin/bash
my_fun() {
echo "$#"
}
echo ‘the number of parameter in "[email protected]" is ‘$(my_fun "[email protected]")
echo ‘the number of parameter in "$*" is ‘$(my_fun "$*")
然後再執行 ./my.sh p1 "p2 p3" p4 就知道 [email protected] 與 $* 差在哪了 ... ^_^

shell學習之[email protected] 與 $* 差在哪?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.