【问题标题】:bash diff fails to found existing files when providing a path variable containing tilde (~) [duplicate]提供包含波浪号 (~) 的路径变量时,bash diff 无法找到现有文件 [重复]
【发布时间】:2017-12-12 06:59:09
【问题描述】:

我在尝试在 bash 脚本中执行 diff 命令时遇到了一个非常令人惊讶的问题。

这是一个说明这一点的工作代码:

#!/bin/bash
cd
mkdir foo bar
head -c 1024 /dev/urandom >foo/qux
head -c 1024 /dev/urandom >bar/qux

# works properly as expected
diff ~/{foo,bar}/qux

folder="~"

# this fails with the ~ inside a variable
diff $folder/{foo,bar}/qux

# cleaning the mess
rm -rf foo bar

所以我的问题是:

为什么? :-)

【问题讨论】:

    标签: bash shell diff tilde


    【解决方案1】:

    ~ 分配给变量时不要引用它。 ~ 只有在你不引用它时才会被 bash 扩展。

    【讨论】:

    • 哈哈哈 :) 非常感谢
    【解决方案2】:

    ~是shell扩展的一个特性。
    双引号将扩展限制为仅三个功能:

    1. 命令替换:$(some command here)`some command here`
    2. 变量替换:$VAR${VAR}
    3. 算术:$((2+2))

    所以当放在双引号内时,~ 不会被扩展

    【讨论】:

    • 这并不一定能解释为什么$folder(未加引号)不扩展波浪号。
    • 什么意思?请举个例子。
    【解决方案3】:

    波浪号扩展仅适用于未加引号的波浪号。在执行对folder 的赋值时必须扩展波浪号,因为波浪号扩展不适用于参数扩展,仅适用于分词和路径名扩展。

    folder=~  # ~ is expanded, and the result is assigned to folder
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 2014-11-25
      • 2017-02-28
      • 1970-01-01
      相关资源
      最近更新 更多