← 返回部落格
·2 min 閱讀

Shell Script 單引號雙引號差異

ShellBashLinux技術筆記

前言

其實這篇沒啥內容,就只是用 Shell Script 時發現一些神奇的小細節。

變數展開的差異

在使用變數的時候要注意一下,可以看下面例子:

$ let test=1
$ echo "$test"
> 1
$ echo '$test'
> $test

發現使用單引號沒辦法正確的顯示 test 的變數內容。

於是就去查了一下 Bash Manual 如下:

Single Quotes(單引號)

Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

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, !. The characters $ and ` retain their special meaning within double quotes.

從上面可以知道特殊字元 $` 需要在雙引號下才會有用。

簡單來說:

  • 單引號:所有字元都是字面值,不做任何展開
  • 雙引號:允許變數展開($)和命令替換(`),其餘字元保持字面值

Reference

  1. Bash Manual
  2. Stack Overflow - Difference between single and double quotes in Bash