我已经执行了以下命令序列:
$ now=$(date)
$ echo _$now_
_
$ echo _ $now _
_ Mon Sep 22 09:53:44 IST 2014 _
Run Code Online (Sandbox Code Playgroud)
为什么输出_$now_只有_?
mur*_*uru 11
来自man bash:
DEFINITIONS
The following definitions are used throughout the rest of this document.
blank A space or tab.
word A sequence of characters considered as a single unit by the shell.
Also known as a token.
name A word consisting only of alphanumeric characters and underscores,
and beginning with an alphabetic character or an underscore. Also
referred to as an identifier.
...
PARAMETERS
A parameter is an entity that stores values. It can be a name, a number,
or one of the special characters listed below under Special Parameters.
A variable is a parameter denoted by a name.
Run Code Online (Sandbox Code Playgroud)
变量只能有字母、数字和下划线。所以now_是一个有效的变量名,并被解释为这样。
您可以用不同的方式分隔变量名称:
_"$now"_
_${now}_
_$now"_"
_$now'_'
Run Code Online (Sandbox Code Playgroud)
或以上任意组合。
请耐心等待,这需要一些解释。
首先,为什么是输出_ $(date) _IS _ Mon Sep 22 03:30:34 MDT 2014 _?因为这从字面上告诉 echo 先输出 _ 然后输出 $(date) 然后 _ 。空格分隔 echo 的变量。
现在尝试echo _$(date),注意_和之间没有空格$(date)。在这种情况下,输出将为_Mon Sep 22 03:32:40 MDT 2014. 这有什么作用?您告诉echo将下划线与$(date).
尝试与 相同的事情_$PWD,它将用下划线连接您的工作目录。现在试试echo $PWD_。输出将为空白。为什么?因为PWD_是不存在的环境变量,正如其他人提到的那样_是环境变量的有效字符,例如$XDG_CURRENT_DESKTOP.
那为什么_$PWD_要给_呢?因为您告诉与不存在的环境变量的输出echo连接_。所以_是打印出来,但$PWD_输出是空白的,所以你真正看到_与空白输出连接起来。