5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シングルクォーテーション、ダブルクォーテーション、バッククォーテーションの違いをまとめた

Posted at

はじめに

Linuxにおいてシングルクォーテーション、ダブルクォーテーション、バッククォーテーションとあるけど結局どれを使えばいいか悩んでしまいませんか?

ここでは、それぞれの違いを解説していきます。

シングルクォーテーション

  • 囲んだ文字を文字としてそのまま解釈します
    • 変数だろうと、何だろうと関係ありません
name="Alice"
echo 'Hello $name'    # 出力: Hello $name
echo 'Current path: $PATH'    # 出力: Current path: $PATH

ダブルクォーテーション

  • 基本は文字列として解釈します
  • 変数があれば変数として解釈します
  • エスケープは解釈してくれます
  • コマンド置換($())は機能します
  • その他の特殊文字(*、?など)は文字列として扱われます
name="Bob"
echo "Hello $name"    # 出力: Hello Bob
echo "Current directory: $(pwd)"    # 出力: Current directory: /home/user
echo "Price: \$100"    # 出力: Price: $100

バッククォーテーション

  • コマンドの実行結果を取得したい時に使用します
  • $(command)と同じ機能を持つ
  • ネストすると可読性が悪くなるので$(command)の使用が推奨されています
current_date=`date`
echo "Today is: $current_date"    # 出力: Today is: Wed Feb 1 10:30:45 JST 2025

# 同じことを$(command)で書く場合:
current_date=$(date)
echo "Today is: $current_date"    # 出力: Today is: Wed Feb 1 10:30:45 JST 2025

# ネストの例
echo "Files in current directory: `ls \`pwd\``"    # バッククォーテーションでは読みにくい
echo "Files in current directory: $(ls $(pwd))"    # $()の方が読みやすい

変数だけで比べてみる

# nameに名前を入れる
name = "Alice"

# シングルクォーテーション
echo 'hello $name'
# そのまま出力される
hello $name

# ダブルクォーテーション
echo "hello $name"
# nameの中身を出力する
hello Alice

# バッククォーテーション
echo `hello $name`
# コマンドじゃないから怒られる
-bash: hello: command not found

まとめ

  • 文字列として扱いたいときはシングルクォーテーション
  • 変数を扱うときはダブルクォーテーション
  • コマンドを扱うときはバッククォーテーション
    • $(command)を推奨
5
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?