2017-07-21 9 views
1

以下のように私はbashスクリプトcountArgs.shを書いた:

./countArgs.sh a b c 
3 
+0

いくつかの関連するQ&Aは参考のためにあります。https://stackoverflow.com/questions/3008695/what-is-the-difference-between-and-in-bash https:/ /stackoverflow.com/questions/2761723/what-is-the-difference-between-and-in-shell-scripts https://stackoverflow.com/questions/21071943/difference-between-and-in-bash-script https ://superuser.com/questions/694501/what-does-mean-as-a-bash-script-function-parameter –

答えて

0
:結果は次のようにいる間、私は、スクリプトの出力は、その入力の数に1を加えなければなりません期待

#!/bin/bash 
function count 
{ 
    echo $# 
} 
count "arg1 [email protected]" 

このに

count "arg1 [email protected]" 

起因:あなたはここに二重引用符で引数リストを同封しているので、

あなたは、カウント3を得ています0関数は、(それぞれ別の行に)のみこれらの3つの引数を取得している:あなたはcount機能でこのprintfラインを配置する場合

arg1 a 
b 
c 

あなたは同じ出力を得ることができます。

count() { 
    printf "%s\n" "[email protected]" 
    echo $# 
} 

注意をどのように最初の位置引数arg1の代わりにarg1 aです。

あなたはarg1 [email protected]の前後に引用符を削除して、それを呼び出す場合:あなたは出力として4を取得します

count arg1 "[email protected]" 

0

つのポイント:

まず、あなたが関数の内部エコーされ、それが$#がないスクリプトを、あなたの数または引数またはあなたの機能を与えることを意味します。

第二に、あなたは引用符"間のパラメータ[email protected]を持つ関数を呼び出しているが、それはこのようになります実際には変数展開後のよう[email protected]はすでに、デフォルトでそれをしない:bash -x

count "arg1 a" "b" "c" 

実行あなたのスクリプトをそして、あなたはそれが機能しているか表示されます。

#!/bin/bash -x 
function count 
{ 
    echo $# 
} 
count "arg1 [email protected]" 
関連する問題