假设我在变量 DIR
中有一个目录路径,并且我想列出该目录。如果我只关心路径中的空格,那么我可以这样做
ls "$DIR"
如果我想在目录路径中也支持单引号和双引号以及其他奇怪的东西,我应该写什么?示例:
DIR="/Users/Mick O'Neil (the \"Terminator\")/Desktop"
echo $DIR # prints /Users/Mick O'Neil (the "Terminator")/Desktop
ls <what should I write here?>
最佳答案
引号不仅适用于空格,也适用于所有内容,因此使用双引号是您此处所需的安全级别。
来自Bash Reference Manual on Quoting :
3.1.2.3 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, ‘!’.
让我们将此字符串存储到文件中以供以后使用。
$ cat file
Mick O'Neil (the "Terminator")
读入变量:
$ filename=$(<file)
检查其值:
$ echo "$filename"
Mick O'Neil (the "Terminator")
使用此值创建一个文件:
$ touch "$filename"
检查是否创建成功:
$ lt "$filename"
-rw-r--r-- 1 me me 0 Mar 1 15:09 Mick O'Neil (the "Terminator")
关于linux - 引用包含引号并在 Bash 中作为变量给出的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42533879/