2015-12-03 109 views
1

將參數傳遞給函數時,我很難理解[email protected]$*之間的區別。

這裏是例子:

function a { 
    echo "-$1-" "-$2-" "-$3-"; 
} 

function b { 
    a "[email protected]" 
} 

function c { 
    a "$*" 
} 

如果電話:

$ b "hello world" "bye world" "xxx" 

它打印:

-hello world- -bye world- -xxx- 

如果電話:

$ c "hello world" "bye world" "xxx" 

它打印:

$ c "hello world" "bye world" "xxx" 
-hello world bye world xxx- -- -- 

發生了什麼事?我無法理解差異,出了什麼問題。

+0

「$ @」與有參數一樣多的字符串; 「$ *」是單個字符串。這個問題有很多問題 - 我會很快找到。 –

+0

謝謝@JonathanLeffler,這是一個很好的閱讀。 – bodacydo

回答

2

$*[email protected]之間沒有區別。它們都會導致參數列表被全局擴展和分詞,因此您不再對原始參數有任何瞭解。你幾乎不想要這個。

"$*"產生單個字符串,這是使用$IFS的第一個字符作爲分隔符(默認情況下爲空格)連接的所有參數。這偶爾是你想要的。

"[email protected]"每個參數產生一個字符串,既不是分詞也不是glob擴展。這通常是你想要的。

+0

謝謝,我發現它並且不加理會。對於那個很抱歉。我現在編輯了我的問題。 – bodacydo