0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【シェルスクリプト】全ての引数を1つの変数で扱う方法

Last updated at Posted at 2024-09-20

$*$@ はシェルスクリプトに渡されたすべての引数を表します。

$*$@ の使い方

  • $*: すべての引数を1つの単一の文字列として扱います。引数はスペースで区切られます。
  • $@: すべての引数を個別の引数として扱います。引数はそれぞれ独立しており、特にダブルクォートで囲むと、空白を含む引数も正しく処理されます。

具体例と $*$@ の違い

example.sh
#!/bin/bash

echo "\$* の出力: $*"
echo "\$@ の出力: $@"

引数を渡して上記のスクリプトを実行します。

$ bash ./example.sh "引数1" "引数 2" "引数3"
$* の出力: 引数1 引数 2 引数3
$@ の出力: 引数1 引数 2 引数3

結果は同じように見えますが、引数をループ処理すると違いがわかります。

example.sh
#!/bin/bash

echo "Using \$*:"
for arg in $*; do
    echo "$arg"
done

echo "Using \$@:"
for arg in "$@"; do
    echo "$arg"
done

このスクリプトを実行すると、次のような出力が得られます。

$ bash ./example.sh "引数1" "引数 2" "引数3"
Using $*:
引数1
引数
2
引数3
Using $@:
引数1
引数 2
引数3

この例では、$* を使用した場合、引数がスペースで分割されてしまい、"引数 2" が2つの引数として扱われてしまいます。一方、$@ を使用した場合、引数は正しく処理され、空白を含む引数も1つの引数として扱われます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?