LoginSignup
1
2

More than 3 years have passed since last update.

bash でシェル変数を文字列内で展開したい場合にはダブルクオートで囲む

Posted at

どういう事か

# シェル変数を定義
$ MY_PARAMETER=hoge

# シングルクオートだと、展開されない
$ echo '$MY_PARAMETER'
$MY_PARAMETER

# ダブルクオートだと、展開される
$ echo "$MY_PARAMETER"
hoge

# こんな感じで使える
MY_INSTANCE_ID=i-xxxxxxxx
aws ec2 describe-instances --instance-ids $MY_INSTANCE_ID

一次情報調べてみたメモ

Quoting (Bash Reference Manual)
https://www.gnu.org/software/bash/manual/html_node/Quoting.html

• Single Quotes: How to inhibit all interpretation of a sequence of characters.
• Double Quotes: How to suppress most of the interpretation of a sequence of characters.

[拙訳]

• シングルクオート: 文字シーケンスのすべての解釈を禁止する
• ダブルクオート: 文字シーケンスのほとんどの解釈を抑制する

「ほとんど」とは?

Double Quotes (Bash Reference Manual)
https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html#Double-Quotes

Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’.

[拙訳]

文字をダブルクオート(")で囲むと引用符内の全文字のリテラル値が保持されるが、例外は '$'、 '`'、 '\'、そして history expansion が有効な場合は '!' となる。

The characters ‘$’ and ‘`’ retain their special meaning within double quotes (see Shell Expansions).

[拙訳]
"$" および "`" は、ダブルクオート内で特別な意味を持つ。(Shell Expansions を参照)

Shell Expansions とは・・・

Shell Expansions (Bash Reference Manual)
https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html

Expansion is performed on the command line after it has been split into tokens. There are seven kinds of expansion performed:

brace expansion
tilde expansion
parameter and variable expansion
command substitution
arithmetic expansion
word splitting
filename expansion

[拙訳]

(入力された文字列たちが)トークンに分割された後、コマンドラインで展開が実行される。
実行される7種類の拡張がある

  1. brace expansion
  2. tilde expansion
  3. parameter and variable expansion
  4. command substitution
  5. arithmetic expansion
  6. word splitting
  7. filename expansion

3.parameter and variable expansion がそれっぽい。

Shell Parameter Expansion: How Bash expands variables to their values.

とリンクがあるので見てみる。

Shell Parameter Expansion (Bash Reference Manual)
https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion

The ‘$’ character introduces parameter expansion, command substitution, or arithmetic expansion.

[拙訳]

$ 文字は、パラメーター展開、コマンド置換、または算術展開を導入する。

...という感じらしい。 bash の機能、多すぎる。

1
2
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
1
2