linux - 引用包含引号并在 Bash 中作为变量给出的文件名

标签 linux bash macos command-line

假设我在变量 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/

相关文章:

php - 我如何阻止来 self 的网络服务器之外的人看到我正在使用的技术(例如,Apache 或 PHP)?

python - 如何在 PyQT 中制作实时更新的可编辑小部件

c++ - 组播波形发生器

c - 是否可以在每条指令后转储内存?

xcode - 从 Cocoa 中的图像中读取 EXIF/IPTC 信息

macos - macOS High Sierra 10.13 上的 PDFtk 服务器

linux - 如何根据用户标识将符号目录链接映射到不同的目录

perl - 在递归 ssh 命令中引用 bash 和 perl

bash - 验证 bash 脚本参数

android - 设置 JAVA_HOME 以正确指向 JDK?