为什么这个使用变量值的 mkdir 命令不起作用?

Wes*_*cts 1 bash

我想创建一个以变量值给出的目录。首先让我们确保可以通过最简单的命令创建目录:

$ mkdir ~/opt
[ec2-user@ip-172-31-15-193 ~]$ ls ~/opt
[ec2-user@ip-172-31-15-193 ~]$ ls -l ~/opt
total 0
Run Code Online (Sandbox Code Playgroud)

使用变量代替硬编码路径的语法是什么?这是已经尝试过的:

$ BDIR="~/opt"
$ mkdir $BDIR
mkdir: cannot create directory ‘~/opt’: No such file or directory
Run Code Online (Sandbox Code Playgroud)

还:

$ mkdir "$BDIR"
mkdir: cannot create directory ‘~/opt’: No such file or directory
Run Code Online (Sandbox Code Playgroud)

LSe*_*rni 5

通常你正在做的事情会奏效。是“~”字符在这里欺骗了您。

您不能在 bash 提示符外使用“~”,因为它是shell 扩展

您需要显式使用该$HOME变量:

BDIR="$HOME/opt"
Run Code Online (Sandbox Code Playgroud)

或者你可以省略引号,这样 BDIR 分配将是扩展路径,它会起作用:

BDIR=~/opt
Run Code Online (Sandbox Code Playgroud)

(如果需要,您可以使用斜杠转义空格 - BDIR=~/path\ with\ spaces)。

或者,正如@Attie 建议的那样,将波浪号保留在引号之外:

BDIR=~"/opt"
Run Code Online (Sandbox Code Playgroud)

  • @Attie 由于我不清楚的原因,`/` 有时也需要不加引号。也就是说,`~"/opt"` * 可能* 有效,但`~/"opt"` * 将* 有效。 (3认同)
  • `~"/opt"` 也可以工作......如果空格有问题的话很有用 (2认同)