これバッシュマニュアル説明する:
について:$*
二重引用符内で拡張が発生すると、単一の単語に展開され、各引数の値は
IFS
特殊変数の最初の文字で区切られます。つまり、変数valueの最初の文字はwhere"$*"
と同じです。"$1c$2c..."
c
IFS
について:$@
二重引用符内で拡張が発生すると、各引数は別々の単語に展開されます。つまり、
"$@"
と同じです"$1" "$2" ...
。
IFS
変数値の最初の文字を提供します。はい実際、これら2つの特定のパラメータが異なる動作を生成する空間では、例を考えることはできないようです。誰でもIFS
別の動作を生成する例(変更なし)を提供できますか?
まだ少し混乱している私のテストは次のとおりです。
#!/usr/bin/env bash
# File: test.sh
# set foo and bar in the global environment to $@ and $*
test_expansion () {
foo="$@"
bar="$*"
}
今テストしてみてください:
. test.sh
test_expansion a b c d
# foo is $@
# bar is $*
for e in "$foo"; do
echo "$e"
done
# a b c d
for e in "$bar"; do
echo "$e"
done
# a b c d
ベストアンサー1
IFS文字を含むコマンドラインから引数(スペースを含む引数など)を渡すと、違いが発生します。違いについては、次のスクリプトを確認してください。
#!/bin/bash
echo 'Here is $*'
for x in "$*"; do
echo " !${x}!"
done
echo ""
echo 'And here is $@'
for x in "$@"; do
echo " !${x}!"
done
exit 0
スペースを使用してパラメータを渡す際の違いを確認します。
./testspace01.sh "This is" a test
Here is $*
!This is a test!
And here is $@
!This is!
!a!
!test!
更新ああ、コマンドラインから渡された内容を変数に割り当てると、いくつかの問題が発生します。 :)
コマンドラインに渡されたすべての項目は配列であることを覚えておいてください。したがって、文字列に配列を割り当てることは、配列に署名するのとは異なります。また、アスタリスクを使用するかアスタリスクを使用するかによって、配列が異なるように処理されます。以下は私のスクリプトの更新版です。
#!/bin/bash
s_star="$*"
echo 'Here is s_star'
for x in "${s_star}"; do
echo " !${x}!"
done
a_star=("$*")
echo ""
echo 'Here is a_star'
for x in "${a_star}"; do
echo " !${x}!"
done
s_at="$@"
echo ""
echo 'Here is s_at'
for x in "${s_at}"; do
echo " !${x}!"
done
a_at=("$@")
echo ""
echo 'Here is a_at (using star)'
for x in "${a_at[*]}"; do
echo " !${x}!"
done
echo ""
echo 'Here is a_at (using at)'
for x in "${a_at[@]}"; do
echo " !${x}!"
done
exit 0
出力は次のとおりです。
./testspace02.sh "This is" a test
Here is s_star
!This is a test!
Here is a_star
!This is a test!
Here is s_at
!This is a test!
Here is a_at (using star)
!This is a test!
Here is a_at (using at)
!This is!
!a!
!test!
ご覧のとおり、さまざまな動作があります。