如何将使用通配符构建并包含空格的路径存储到变量中

mhu*_*lse 5 shell bash quoting wildcards variable

这是情况(我使用的是 Mac,OS X El Capitan):

# This works:

$ cd /Applications/Adobe\ Illustrator*/Cool\ Extras.localized/en_US/Templates/;

# These do not work:

$ INSTALL_DIR=/Applications/Adobe\ Illustrator*/Cool\ Extras.localized/en_US/Templates;
$ cd $INSTALL_DIR
# Moves me here: /Applications/Adobe

$ cd "$INSTALL_DIR"
-bash: cd: /Applications/Adobe Illustrator*/Cool Extras.localized/en_US/Templates: No such file or directory

$?cd "${INSTALL_DIR}"
-bash: cd: /Applications/Adobe Illustrator*/Cool Extras.localized/en_US/Templates: No such file or directory
Run Code Online (Sandbox Code Playgroud)

我的目标是用$INSTALL_DIRtar像这样:

$ tar -xz $SOURCE_ZIP --strip-components 1 -C $INSTALL_DIR "*.ait";
Run Code Online (Sandbox Code Playgroud)

不幸的是,-C(更改到目标目录)不喜欢$INSTALL_DIR; 中的空格。如果我使用引号,我将无法*工作。

有没有一种优雅的方法来处理这种情况?

Cha*_*ark 5

当 * 没有被引用时,shell 在运行命令之前扩展参数列表。它将扩展参数列表传递给程序。

当 * 出现在带引号的字符串中时,它在传递给程序之前不会被 shell 扩展。

尝试扩展路径,将其分配给另一个变量,然后在将其作为参数传递时引用第二个变量。

  • @mhulse - `cd /Applications/"Adobe Illustrator"*/"Cool Extras.localized/en_US/Templates" && cd - && tar ... | 焦油 ... -“C$OLDPWD” ...` (3认同)
  • 啊,这个有效:`INSTALL_DIR=$(cd /Applications/Adobe\ Illustrator*/Cool\ Extras.localized/en_US/Templates; pwd);`。然后在我的 `tar` 行中,我将变量用引号引起来(例如 `"$INSTALL_DIR"`)。感谢乍得的提示和帮助,我真的很感激! (2认同)